pandas 无法从函数内向panda Dataframe 添加新列

js4nwp54  于 2023-01-01  发布在  其他
关注(0)|答案(2)|浏览(154)

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)给了我键错误

lo8azlld

lo8azlld1#

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

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
deyfvvtc

deyfvvtc2#

尝试将值保存到列表中,然后将其分配到新列“full”

full.append(l)

则在循环结束之后:

df2['full'] = full

相关问题