熊猫:迭代并返回:索引,下一个索引和行

时间:2019-09-12 17:04:44

标签: python pandas dataframe

我有一个这样的数据框:

df = pd.DataFrame({0: [1, 4, 7, 10], 1: [5, 7, 9, 12], 2: ['v=55', 'g=40', 'd=84', 'f=31']})
s = pd.Series([0, 15, 30, 45])
df.set_index([s], inplace=True)

我想遍历行并返回:

  • 索引[i],
  • 索引[i + 1],
  • 从第2列中拆分出的数值,例如(v = 55应该给出55)。

我尝试使用迭代来获取2个索引和该行:

ind=0
for index, row in df.iterrows(): 
  if index==0: #continue to start loop from second value
    continue
  splitvalue= row[2].split('=')[1]
  print ( ind, index, splitvalue) #print ind, next index, splitvalue
  ind=index #update ind with current index

但是,这样返回的splitvalue是 next 而不是当前

当前答案:

ind:0, index=15, splitvalue:'40' 
ind:15, index=30, splitvalue:'84'....

想要的答案:

ind:0, index=15, splitvalue:'55'
ind:15, index=30, splitvalue:'40'....

1 个答案:

答案 0 :(得分:1)

问题是,当您确实要在第一行开始打印时,您正在获取该行的值,然后在第二行开始打印。您可以使用df.loc[ind]df.index == ind处获取行。

ind=0
for index, row in df.iterrows(): 
    if index==0: #continue to start loop from second value
        continue
    splitvalue = df.loc[ind][2].split('=')[1]
    print (f"ind:{ind}, index:{index}, splitvalue:{splitvalue}") #print ind, next index, splitvalue
    ind = index #update ind with current index

让我知道这种解释是否有意义。