[英]unable to add a new column to a pandas dataframe from within a function
it_json are columns that contain lists, for each row in a dataframe I want to add the lists in a fresh column called full 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
but list_columns(df) is giving me key error但是 list_columns(df) 给了我关键错误
Try to save the values into a list then assign them to the new columns "full"尝试将值保存到列表中,然后将它们分配给“完整”的新列
full.append(l)
then after the loop ends:然后在循环结束后:
df2['full'] = full
You are allocating values to a column that doesn't exist yet, so create an empty column before adding values.您正在将值分配给尚不存在的列,因此在添加值之前创建一个空列。
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.