繁体   English   中英

无法从 function 向 pandas dataframe 添加新列

[英]unable to add a new column to a pandas dataframe from within a function

it_json 是包含列表的列,对于 dataframe 中的每一行,我想将列表添加到名为 full 的新列中

def list_columns(df):
    df2=df.copy()
    for index,row in df.iterrows():
        # print(row)
        l=[]
        if row['it_json_1']:
            l+=row['it_json_1']
        if row['it_json_2']:
            l+=row['it_json_2']
        if row['it_json_3']:
            l+=row['it_json_3']
        if row['it_json_4']:
            l+=row['it_json_4']
        df2['full'][index]= l
    return df2

但是 list_columns(df) 给了我关键错误在此处输入图像描述

尝试将值保存到列表中,然后将它们分配给“完整”的新列

 full.append(l)

然后在循环结束后:

 df2['full'] = full

您正在将值分配给尚不存在的列,因此在添加值之前创建一个空列。

def list_columns(df):
df2=df.copy()
for index,row in df.iterrows():
    # print(row)
    l=[]
    l['full'] = np.nan
    if row['it_json_1']:
        l+=row['it_json_1']
    if row['it_json_2']:
        l+=row['it_json_2']
    if row['it_json_3']:
        l+=row['it_json_3']
    if row['it_json_4']:
        l+=row['it_json_4']
    df2['full'][index]= l
return df2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM