在带有熊猫的for循环内的CSV数据帧中添加新行

时间:2020-04-16 15:03:42

标签: python pandas csv dataframe

你好,我真的很受困扰,无法解决这个问题,我非常感谢任何帮助或指导。我曾尝试过几次以不同的方式问这个问题,但在完成任务方面没有取得完全的成功。

我试图从电子表格“ a.csv”的每一行中获取一个单元格,然后使用该值检查多个正则表达式,以及另一个电子表格“ b.csv”中另一行是否存在项目

现在我已经可以使用所有正则表达式了,当我将数据打印到屏幕上时,它可以完美地显示所有数据并正确执行检查。

问题在于我无法在循环和if语句中将“ b.csv”中的值应用于“ a.csv”(仅将“ 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

我认为该错误与嵌套循环以及它如何遍历数据有关,但是我正在拔头发。如果我尝试错误地进行此操作,将极大地帮助您获得答案或指导。

1 个答案:

答案 0 :(得分:1)

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