简体   繁体   中英

How to add a value to specific rows and columns on pandas?

So here's the deal, I have this dataframe, lets kindly name it lovely_df:

   foo? fah? boo? Nice Numbers
0  foo  fah  boo  10
1  meh  fah  boo  20
2  meh  fah  boo  30
3  foo  fah  boo  40
4  meh  fah  boo  50

tried to do it like that:


lovely_df.loc[lovely_df['foo?'] == 'meh',:]['Nice Numbers'].add(1)

And it returns me this:

   Nice Numbers
1  21
2  31
4  51

Which would be ok if it was saved into lovely_df, but it didn't, so i tried:


lovely_df.loc[lovely_df['foo?'] == 'meh',:]['Nice Numbers'] = lovely_df.loc[lovely_df['foo?'] == 'meh',:]['Nice Numbers'].add(1)

It actually works but it gives me:

<input>:1: 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

So this is it, i just wanted to add a specific number to a single column of a few rows without Python crying on me.

Thanks guys!

You can use numpy.where with your condition

lovely_df['new_col'] = np.where(lovely_df['foo?'] == 'meh',
                                lovely_df['Nice Numbers'].add(1),
                                lovely_df['Nice Numbers'])
print(lovely_df)

  foo? fah? boo?  Nice Numbers  new_col
0  foo  fah  boo            10       10
1  meh  fah  boo            20       21
2  meh  fah  boo            30       31
3  foo  fah  boo            40       40
4  meh  fah  boo            50       51

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