簡體   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