Python Pandas - 迭代并向空白列添加数据

Sco*_*tEU 0 python pandas

我试图遍历数据帧,对每一行进行分类,并将输出添加到新列的行尾.

它似乎是为每一行添加相同的分类

dfMach = pd.read_csv("C:/Users/nicholas/Desktop/machineSum.csv", encoding='latin-1')
dfNew = dfMach
dfNew["Classification"] = ""

for index, row in dfMach.iterrows():
    aVar = dfMach['Summary'].iat[0]
    aClass = cl.classify(aVar)
    dfNew['Classification'] = aClass
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

谢谢

Flo*_*oor 5

使用apply而不是显式循环即

 dfMach['Classification'] = dfMach['Summary'].apply(cl.classify)
Run Code Online (Sandbox Code Playgroud)

在您的代码中需要纠正的几个简单错误和一些改进,即

dfNew = dfMach.copy() # dfNew = dfMach This will not let you create a new copy so you have to use dfMach.copy()

dfNew["Classification"] = ""

for index, row in dfMach.iterrows(): 
    # As @jez suggested we need to use loc for assignemnt 
    dfNew.loc[index, 'Classification'] = cl.classify(row['Summary'])
Run Code Online (Sandbox Code Playgroud)