python - 使用 Pandas 在 for 循环中向 CSV 数据框添加新行
问题描述
您好,我真的被卡住了,无法解决这个问题,非常感谢任何帮助或指导。我尝试过几次不同的方式来问这个问题,但在完成我的任务时没有完全成功。
我试图从电子表格“a.csv”中的每一行中获取一个单元格,然后使用该值检查多个正则表达式,以及另一个电子表格“b.csv”中的另一行是否存在项目
现在,我已经使用所有正则表达式进行了这项工作,当我将数据打印到屏幕上时,它完美地运行,向我展示了所有数据并正确地进行了检查。
问题在于我不能从“b.csv”中获取值并应用于循环内的“a.csv”和 if 语句(仅将“b.csv”中的值应用于“a”中的正确行.csv")
这是我目前的代码:
import pandas as pd
import re
df1 = pd.read_csv('a.csv', sep=",")
df2 = pd.read_csv('b.csv', sep=",")
for index, row in df1.iterrows():
for i, r in df2.iterrows():
if r['Model'] in row['Title']:
df1[index, 'Tag'] = r['Tag']
# if you print df1[index, 'Tag'] HERE it prints the correct tag for each index/row and then possible will continue searching through b.csv with the same index in a.csv which is what i need to do as there may be mutiple of the same.
# This is the information I need to put in a new row under the index row but currently it only adds to the existing row and then gets wiped after another search.
#if you print df1 here it only applies to a couple of rows and not all of them.
df1.to_csv('a.csv', sep=",", index=False)
A.CSV - 示例数据
IDNumber Title
1 Vauxhall Astra Model H 92-93
2 VW Golf MK2 GTI 90-91
3 BMW 1 Series 89-93
B.CSV - 示例数据
Manufacturer Model Type Year Tag
VW Golf MK2 1990|1991|1993 1000
VW Golf MK2 GTI 1990|1991|1993 1001
VW Golf MK2 1896|1897|1898|1899 1002
Vauxhall Astra Model H 1991|1992|1993|1994 1003
BMW 2 Series 2000|2001|2002 1004
A.CSV - 我需要的输出
IDNumber Title Tag
1 Vauxhall Astra Model H 92-93
1003
2 VW Golf MK2 GTI 90-91
1000
1001
3 BMW 1 Series 89-93
我相信这个错误与嵌套循环以及它如何遍历数据有关,但我正在拔头发。如果我尝试不正确地执行此操作,将非常感谢答案或指导。
解决方案
一种可能的方法是在数据帧的末尾添加新行并将 IDNumber 存储在其中。在循环结束时,您可以对 IDNumber 上的数据框进行排序,并在没有标题的行上将其设置为空白。这是一个可能的代码:
for index, row in df1.iterrows():
for i, r in df2.iterrows():
if r['Model'] in row['Title']:
ix = len(df1)
df1.loc[ix, 'Tag'] = r['Tag']
df1.loc[ix, 'IDNumber'] = row['IDNumber']
df1 = df1.sort_values(['IDNumber']).reset_index(drop=True)
df1.loc[df1['Title'].isna(), 'IDNumber'] = ''
df1 = df1.fillna('')
你终于得到:
IDNumber Title Tag
0 1 Vauxhall Astra Model H 92-93
1 1003
2 2 VW Golf MK2 GTI 90-91
3 1000
4 1001
5 1002
6 3 BMW 1 Series 89-93
注意:您还会得到 1002 标签,因为此代码没有检查年份...
推荐阅读
- python - 打印带有所需位置参数的嵌套子解析器的帮助
- node.js - 如何使用javascript增量方法增加数据库中的点击次数?
- django-models - 在创建新类 Airport 并在 makemigrations 引发 IntegrityError 后迁移它时对航班进行一些更改之后
- http-status-code-500 - zappa:对“/”的 GET 请求产生了 500 响应代码
- python - 如何在匹配条件的 2 列中获取具有相同值且在其他两列中具有不同值的行
- google-chrome-extension - 后台脚本和隐身后台脚本之间的通信(使用“隐身”时:“拆分”模式)
- c++ - 与同一数据库建立两个连接时出现“mysql服务器已消失”错误
- php - accounts.google.com 在 Laravel 社交名流中重定向您的次数过多
- angular7 - Ngfor 循环内的条件
- python - 在烧瓶中使用 Sqlalchemy 过滤 Json Postgres 列(从字符串类型转换为 Json 之后)