想象一下,一个数据帧中有三列和一定数量的行。第一列是随机值,第二列是名称,第三列是年龄。
我想搜索此数据帧的每一行(第一行),并查找第一列中何时出现值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.
答案 0 :(得分:1)
假设您有一个像这样的数据框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