将列添加到pandas数据帧中,但逐行添加

时间:2014-04-21 12:41:23

标签: pandas dataframe

我似乎没有找到一个完全符合我需要的问题。

我逐行迭代pandas数据帧。 然后根据行中的每个项目,我对其他一组dataframea文件执行一些复杂的操作并进行回归。那个回归的输出,我想作为一个列插入到这个原始数据帧中。尝试了一些事情,但它没有用。

这是我正在尝试的

import pandas as pd
...
dfd = <my dataframe>

dfd['new column'] = 0  #initializing with 0. THis also did not work

for i, row in dfd.iterrow():
    <do some complex operation>
    res = result of complex operation
    row['new column'] = res

print dfd.to_string()

在这一点上,我仍然看到所有在新专栏中登记为0

1 个答案:

答案 0 :(得分:2)

要在行迭代期间更改col的值,请尝试此

df['new column'].iloc[i] = res

重新实现您的功能可能更简洁,如下所示

def complex_operation(row):
    ...
    return res

dfd['new column'] = dfd.apply(complex_operation, axis=1)
相关问题