首页 > 解决方案 > 如何搜索 CSV 文件的一行(第 1 行),但同时搜索下一行(第 2 行)?

问题描述

想象一下数据框中有三列和一定数量的行。第一列是随机值,第二列是名称,第三列是年龄。

我想搜索此数据帧的每一行(第一行)并查找值 1 何时出现在第一列中。然后同时,我想知道如果值 1 确实存在于列中,值 2 是否出现在 SAME 列中但在下一行中。

如果是这种情况。将第一行、值、名称和年龄复制到一个空的数据框中。每次满足此条件时,将这些行复制到一个空数据框中

EmptyDataframe = pd.DataFrame(columns['Name','Age'])
csvfile = pd.DataFrame(columns['Value', 'Name', 'Age'])


row_for_csv_dataframe = next(csv.iterrows())

for index, row_for_csv_dataframe in csv.iterrows():
    if row_for_csv_dataframe['Value'] == '1':

    # How to code this:
    # if the NEXT row after row_for_csv_dataframe finds the 'Value' == 2
    # then copy 'Age' and 'Name' from row_for_csv_dataframe into the empty DataFrame.

标签: python-3.xpandas

解决方案


假设您有这样的数据框data

   Value  Name  Age
0      1  Anne   10
1      2  Bert   20
2      3  Caro   30
3      2  Dora   40
4      1  Emil   50
5      1  Flip   60
6      2  Gabi   70

你可以做这样的事情,虽然这可能不是最有效的:

iterator1 = data.iterrows()
iterator2 = data.iterrows()
iterator2.__next__()
for current, next in zip(iterator1,iterator2):
  if(current[1].Value==1 and next[1].Value==2):
    print(current[1].Value, current[1].Name, current[1].Age)

并会得到这个结果:

1 Anne 10
1 Flip 60

推荐阅读