熊猫使用Apply功能更新多列

Karthikeyan KR

我正在使用函数apply更新数据框。

但是现在我需要使用此功能修改多列,

这是我的示例代码:

def update_row(row):
    listy = [1,2,3]
    return listy

dp_data_df[['A', 'P','Y']] = dp_data_df.apply(update_row, axis=1)

它抛出以下错误:

ValueError: shape mismatch: value array of shape (10,) could not be broadcast to indexing result of shape (3,10)

提前致谢。

耶斯列尔

您可以返回pd.Series

dp_data_df = pd.DataFrame({'A':[3,5,6,6],
                           'B':[6,7,8,9],
                           'P':[5,6,7,0],
                           'Y':[1,2,3,4]})
print (dp_data_df)
   A  B  P  Y
0  3  6  5  1
1  5  7  6  2
2  6  8  7  3
3  6  9  0  4

def update_row(row):
    listy = [1,2,3]
    return pd.Series(listy)

dp_data_df[['A', 'P','Y']] = dp_data_df.apply(update_row, axis=1)
print (dp_data_df)
   A  B  P  Y
0  1  6  2  3
1  1  7  2  3
2  1  8  2  3
3  1  9  2  3

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章