猿问

如何为熊猫的特定行和列添加值?

所以这是交易,我有这个数据框,让我们将其命名为 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

试图这样做:



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

它返回给我:


   Nice Numbers

1  21

2  31

4  51

如果将其保存到 lovely_df 中就可以了,但它没有,所以我尝试了:



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

它确实有效,但它给了我:


<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

所以就是这样,我只是想在几行的单列中添加一个特定的数字,而不会让 Python 对我哭泣。


多谢你们!


慕的地6264312
浏览 105回答 1
1回答

哆啦的时光机

您可以numpy.where根据自己的情况使用lovely_df['new_col'] = np.where(lovely_df['foo?'] == 'meh',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lovely_df['Nice Numbers'].add(1),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lovely_df['Nice Numbers'])print(lovely_df)&nbsp; foo? fah? boo?&nbsp; Nice Numbers&nbsp; new_col0&nbsp; foo&nbsp; fah&nbsp; boo&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 10&nbsp; &nbsp; &nbsp; &nbsp;101&nbsp; meh&nbsp; fah&nbsp; boo&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 20&nbsp; &nbsp; &nbsp; &nbsp;212&nbsp; meh&nbsp; fah&nbsp; boo&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 30&nbsp; &nbsp; &nbsp; &nbsp;313&nbsp; foo&nbsp; fah&nbsp; boo&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 40&nbsp; &nbsp; &nbsp; &nbsp;404&nbsp; meh&nbsp; fah&nbsp; boo&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 50&nbsp; &nbsp; &nbsp; &nbsp;51
随时随地看视频慕课网APP

相关分类

Python
我要回答