【问题标题】:New column using apply function on other columns in dataframe在数据框中的其他列上使用应用函数的新列
【发布时间】:2018-10-28 16:16:27
【问题描述】:

我有一个数据框,其中三列是数据的坐标(“H_x”、“H_y”和“H_z”)。我想计算数据的半径向量并将其作为新列添加到我的数据框中。但是我对熊猫应用功能有一些问题。 我的代码是:

def radvec(x, y, z):
    rv=np.sqrt(x**2+y**2+z**2)
    return rv

halo_field['rh_field']=halo_field.apply(lambda row: radvec(row['H_x'], row['H_y'], row['H_z']), axis=1)

我得到的错误是:

group_sh.py:78: 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
halo_field['rh_field']=halo_field.apply(lambda row: radvec(row['H_x'], row['H_y'], row['H_z']), axis=1)

我得到了我想要的列,但我仍然对这个错误消息感到困惑。 我知道这里有类似的问题,但我找不到如何解决我的问题。我对python相当陌生。你能帮忙吗?

编辑: halo_field 是另一个数据帧的一部分:

halo_field = halo_res[halo_res.N_subs==1] 

【问题讨论】:

  • 您是如何在代码中定义halo_field earlier 的?很可能它是另一个数据帧的 slice这就是您的错误的原因。
  • 是的,它是另一个数据帧的切片:halo_field=halo_res[halo_res.N_subs==1]

标签: python pandas apply


【解决方案1】:

问题是您正在使用切片,这可能是模棱两可的:

halo_field = halo_res[halo_res.N_subs==1]

你有两个选择:

制作副本

您可以显式复制您的数据框以避免警告并确保您的原始数据框不受影响:

halo_field = halo_res[halo_res.N_subs==1].copy()
halo_field['rh_field'] = halo_field.apply(...)

有条件地处理原始数据帧

使用带有布尔掩码的pd.DataFrame.loc 来更新您的原始数据框:

mask = halo_res['N_subs'] == 1
halo_res.loc[mask, 'rh_field'] = halo_res.loc[mask, 'rh_field'].apply(...)

不要使用apply

附带说明,在 either 场景中,您可以避免 apply 用于您的功能。例如:

halo_field['rh_field'] = (halo_field[['H_x', 'H_y', 'H_z']]**2).sum(1)**0.5

【讨论】:

  • 是的,这行得通,我将继续制作副本!非常感谢你。很抱歉,我无法为您的答案投票,作为新用户,我没有足够的声誉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
相关资源
最近更新 更多