简体   繁体   中英

Insert into a pandas dataframe slice of another slice from the same dataframe

I have a pandas.DataFrame like this one:

df = pd.DataFrame({'val_1': [np.nan, np.nan, np.nan, 2.34, 2.21, 2.45], 
                   'val_2': [3.1, 3.02, 3.67, np.nan , np.nan, np.nan], 
                   'group': [1, 1, 1, 2, 2, 2]})

df

    val_1   val_2  group
0   NaN     3.10    1
1   NaN     3.02    1
2   NaN     3.67    1
3   2.34    NaN     2
4   2.21    NaN     2
5   2.45    NaN     2

I want to fill the NaN values from column val_1 that belong to group 1 with the values from the column val_1 from the group 2 . I tried using:

df.loc[df['group']==1, 'val_1'] = df.loc[df['group']==2, 'val_1'] 

I'm expecting as a result the following:

    val_1   val_2  group
0   2.34    3.10    1
1   2.21    3.02    1
2   2.45    3.67    1
3   2.34    NaN     2
4   2.21    NaN     2
5   2.45    NaN     2

But instead I'm getting this:

    val_1   val_2  group
0   NaN     3.10    1
1   NaN     3.02    1
2   NaN     3.67    1
3   2.34    NaN     2
4   2.21    NaN     2
5   2.45    NaN     2

How can I perform that action properly? The solution needs to be extensible to a larger dataframe. Thank you in advance!

Fix your code adding the .values

df.loc[df['group']==1, 'val_1'] = df.loc[df['group']==2, 'val_1'].values
df
Out[300]: 
   val_1  val_2  group
0   2.34   3.10      1
1   2.21   3.02      1
2   2.45   3.67      1
3   2.34    NaN      2
4   2.21    NaN      2
5   2.45    NaN      2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM