New column using apply function on other columns i

2019-03-01 02:53发布

问题:

I have a dataframe where three of the columns are coordinates of data ('H_x', 'H_y' and 'H_z'). I want to calculate radius-vector of the data and add it as a new column in my dataframe. But I have some kind of problem with pandas apply function. My code is:

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)

The error I'm getting is:

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)

I get column that I want, but I'm still confused with this error message. I'm aware there are similar questions here, but I couldn't find how to solve my problem. I'm fairly new to python. Can you help?

Edit: halo_field is a slice of another dataframe:

halo_field = halo_res[halo_res.N_subs==1] 

回答1:

The problem is you're working with a slice, which can be ambiguous:

halo_field = halo_res[halo_res.N_subs==1]

You have two options:

Work on a copy

You can explicitly copy your dataframe to avoid the warning and ensure your original dataframe is unaffected:

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

Work on the original dataframe conditionally

Use pd.DataFrame.loc with a Boolean mask to update your original dataframe:

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

Don't use apply

As a side note, in either scenario you can avoid apply for your function. For example:

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