首页 > 解决方案 > 使用 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

我相信这个错误与嵌套循环以及它如何遍历数据有关,但我正在拔头发。如果我尝试不正确地执行此操作,将非常感谢答案或指导。

标签: pythonpandascsvdataframe

解决方案


一种可能的方法是在数据帧的末尾添加新行并将 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 标签,因为此代码没有检查年份...


推荐阅读