Python 将空字符列添加到数据帧的工作方式很奇怪
我有一个数据框,我想在其中添加新的列“being_叙事”。数据帧信息如下所示: Dataframe具有以下行索引: 我尝试使用以下命令添加字符串类型的新列:Python 将空字符列添加到数据帧的工作方式很奇怪,python,pandas,dataframe,numpy-slicing,Python,Pandas,Dataframe,Numpy Slicing,我有一个数据框,我想在其中添加新的列“being_叙事”。数据帧信息如下所示: Dataframe具有以下行索引: 我尝试使用以下命令添加字符串类型的新列: explain_instance_to_explain_df_sorted_top6['being_narrative'] = "" 但是,它给出了带有复制警告的设置: _主警告:1:设置为带有COPYWARNING: 试图在数据帧切片的副本上设置值。 尝试改用.loc[row\u indexer,col\u indexer]=val
explain_instance_to_explain_df_sorted_top6['being_narrative'] = ""
但是,它给出了带有复制警告的设置:
_主警告:1:设置为带有COPYWARNING:
试图在数据帧切片的副本上设置值。
尝试改用.loc[row\u indexer,col\u indexer]=value
当我尝试在不同的数据帧上使用上述命令时,没有收到此警告:
此外,没有为该列指定新值
explain_instance_to_explain_df_sorted_top6['being_narrative'] = ""
for index,row in explain_instance_to_explain_df_sorted_top6.iterrows() :
row['being_narrative']= str(np.where( row.obs_instance_to_explain not in (0,1) and row.features not in ('NUM_CASES'),' being '+str(row.obs_instance_to_explain),''))
运行上述分配后,新列仍为空:
但是,这是单独起作用的,如下所示:
似乎问题在于数据帧。有什么问题吗?提前谢谢
更新:
尝试使用@Aryerez建议使用.loc约定,首先删除列,然后使用:
explain_instance_to_explain_df_sorted_top6.loc[:, 'being_narrative'] = ""
但再次得到警告,显然数据帧存在问题:
为避免出现警告,请使用以下内容创建新列:
explain\u instance\u To\u explain\u df\u sorted\u top6.loc[:,“being\u reprotation”]=“”
。至于您得到的输出,它只是索引和列的值,它们是空字符串,因此不可见。@Aryerez尝试使用iloc约定,但仍然得到警告,如上面讨论的更新中所示。另外,很抱歉,我误解了索引值,但问题确实存在,因为当我尝试使用df.iterrows()约定为该列分配新值时,它根本不会被分配。将更新此有问题的信息。