python-3.x - 如何搜索 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.
解决方案
假设您有这样的数据框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
推荐阅读
- python-3.x - 根据特定条件生成带有 ffill 的行 - pandas
- python - 如何访问和过滤具有多个值的字典?
- mysql - Mysql:如果没有更多引用(在几个中),则自动删除行
- python - NameError:名称“pydotplus”未定义
- sql-server - 导出 .dtsx 文件并添加到 Visual Studio 中的新项目
- c++ - 将 XML 命名空间 URI 解析为 Poco DOM C++ 中的属性
- python - 将每行都是列表的数据框拆分为列
- azure-active-directory - Azure SSO(示例代码)在 IIS 中的自定义网站中托管时不起作用
- matplotlib - 为什么我的图表在 python.matplotlib 中以这种方式绘制?
- python - ctypes c_uint32 被错误地从 python 传递到 Cpp