我正在尝试在数据帧的末尾添加新列,但是该值根据其他两列中的信息而有所不同。总体结果应为新列,其中另一列的绝对值已重新缩放,以绝对值除以该列中的最高值
我试图屏蔽数据帧,但是在for循环结束时,整个df都没有发生任何变化(即,当我要求dr.head()时,没有新列)
for n in list(top_dict.keys()):
for c in clusters:
mask=(data.season==n) & (data.cluster==c)
for attribute in panel:
ratio_list=[]
for kpi in data[mask][attribute]:
try:
ratio_list.append(kpi/top_dict[n][c][attribute]['Score'])
except:
ratio_list.append(0)
data[mask]['%s_ratio'%attribute]=ratio_list
运行代码后,旧的数据框保持不变,并且不添加任何额外的列。
数据样本:
season cluster val_1 val_2 val_3
2014 A 0 5 8
2016 B 1 7 0
2015 C 2 9 8
2015 C 3 3 9
2017 A 4 5 1
答案 0 :(得分:0)
您应该已经看到了这个相当明确的警告:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
这意味着data[mask]
只是原始数据帧上的一个切片,不应尝试更改其元素,而应使用全局loc
还原为原始数据帧:
data.loc[mask, '%s_ratio'%attribute]=ratio_list
这应该足以消除警告并更改数据框。