首页 文章

更新pandas数据帧值会分配Nan

提问于
浏览
0

我有一个包含3列的数据框:Col1,Col2和Col3 .

玩具示例

d = {'Col1':['hello','k','hello','we','r'],
     'Col2':[10,20,30,40,50],
     'Col3':[1,2,3,4,5]}
df = pd.DataFrame(d)

得到:

Col1  Col2  Col3
0  hello    10     1
1      k    20     2
2  hello    30     3
3     we    40     4
4      r    50     5

我正在选择 Col2 的值,以便 Col1 中的值为'hello'

my_values = df.loc[df['Col1']=='hello']['Col2']

这会给我一个系列,在那里我可以看到 Col2 的值以及索引 .

0    10
2    30
Name: Col2, dtype: int64

现在假设我想将此值分配给Col3 .

我只想替换那些值(索引0和2),保持Col3中的其他值不被修改

我试过了:

df['Col3'] = my_values

但这会将 Nan 分配给其他值(Col1不是你好的那些)

Col1  Col2  Col3
0  hello    10    10
1      k    20   NaN
2  hello    30    30
3     we    40   NaN
4      r    50   NaN

如何更新Col3中的某些值而不更改其他值?

Col1  Col2  Col3
0  hello    10    10
1      k    20   2
2  hello    30    30
3     we    40   4
4      r    50   5

简而言之:

拥有my_values我想把它们放在Col3中

1 回答

  • 1

    或者只是基于 np.where

    df['Col3']=np.where(df['Col1'] == 'hello',df.Col2,df.Col3)
    

    如果基于你的myvalue

    df.loc[my_values.index,'col3']=my_values
    

    或者你可以做 update

    df['Col3'].update(my_values)
    

相关问题