填补缺失的NAs无法正常工作

问题描述 投票:0回答:1

我有SettingWithCopyWarning的问题,价值没有被取代。我在这个网站上进行了非常广泛的搜索,而我在处理SettingWithCopyWarning方面所看到的就是使用copy()。但是,尝试用col2中的值替换col1中的任何缺失值,即使使用以下代码也不适合我 -

import numpy as  np
import pandas as pd
import copy
test = pd.DataFrame({'a':[1,np.nan,3], 'b':[5,6,7]})
test2 = test.copy()
test3 = test.copy()
test2.loc[np.isnan(test2['a']) & (np.isnan(test2['b']) == False)]['a'] = 
    test3.loc[np.isnan(test3['a']) & (np.isnan(test3['b']) == False)]['b']

print(test2)

第一栏中的NaN仍在那里,我仍然得到SettingWithCopyWarning。我错过了什么?

pandas
1个回答
0
投票

我相信你需要:

test = pd.DataFrame({'a':[1,np.nan,3], 'b':[5,6,7]})

test['a'] = test['a'].fillna(test['b'])
#alternative
#test['a'] = test['a'].combine_first(test['b'])
print (test)
     a  b
0  1.0  5
1  6.0  6
2  3.0  7

编辑:

loc解决方案非常相似,只删除][以避免chaining indexing

test2.loc[np.isnan(test2['a']) & (np.isnan(test2['b']) == False), 'a'] = \
    test3.loc[np.isnan(test3['a']) & (np.isnan(test3['b']) == False), 'b']
print (test2)
     a  b
0  1.0  5
1  6.0  6
2  3.0  7
© www.soinside.com 2019 - 2024. All rights reserved.