用python系列中的值替换数据帧中的NaN值
我有一张桌子用python系列中的值替换数据帧中的NaN值,python,pandas,Python,Pandas,我有一张桌子 id count 0 10 3 1 20 4 2 30 5 3 40 NaN 4 50 NaN 5 60 NaN 6 70 NaN 我还有另一个熊猫系列 0 1000 1 2000 2 3000 3 4000 我想做的是用序列s中的相应值替换df中的NaN值。 我的最终输出应该是 id cou
id count
0 10 3
1 20 4
2 30 5
3 40 NaN
4 50 NaN
5 60 NaN
6 70 NaN
我还有另一个熊猫系列
0 1000
1 2000
2 3000
3 4000
我想做的是用序列s中的相应值替换df中的NaN值。
我的最终输出应该是
id count
0 10 3
1 20 4
2 30 5
3 40 1000
4 50 2000
5 60 3000
6 70 4000
有什么办法可以做到这一点吗
提前感谢。就这么简单:
df.count[df.count.isnull()] = s.values
由于列
计数中NaN
值的长度不同,系列的length
存在问题。所以您需要系列
按NaN的长度
:
s = pd.Series({0: 1000, 1: 2000, 2: 3000, 3: 4000, 5: 5000})
print (s)
0 1000
1 2000
2 3000
3 4000
5 5000
dtype: int64
df.loc[df['count'].isnull(), 'count'] =
s.reindex(np.arange(df['count'].isnull().sum())).values
print (df)
id count
0 10 3.0
1 20 4.0
2 30 5.0
3 40 1000.0
4 50 2000.0
5 60 3000.0
6 70 4000.0
在这种情况下,我更喜欢iterrows的可读性
counter = 0
for index, row in df.iterrows():
if row['count'].isnull():
df.set_value(index, 'count', s[counter])
counter += 1
我可以补充一点,dataframe+系列的这种“合并”有点奇怪,而且容易出现奇怪的错误。如果您能够以某种方式将序列转换为与数据帧相同的格式(即添加一些索引/列标记,那么合并功能可能会更好地为您服务)。您可以使用数据帧中的np.nan
索引重新索引序列,而不是使用序列中的fillna()
:
s.index = np.where(df['count'].isnull())[0]
df['count'] = df['count'].fillna(s)
print(df)
id count
0 10 3.0
1 20 4.0
2 30 5.0
3 40 1000.0
4 50 2000.0
5 60 3000.0
6 70 4000.0
我编辑了我的问题,我系列的索引从0开始,而不是从3开始。获取此错误'function'对象没有属性'isnull'
需要df.loc[df['count'].isnull(),'count']=s.values
@jezrael在用代码替换后出错必须具有相等的len键和值当使用ndarray设置时
我编辑了我的问题,我系列的索引从0开始,而不是从3开始。我添加了解决方案,请检查。请在此处阅读设置值:^我同意。耶斯雷尔的另一个解决方案很有意义,但只是在一些头颅撕裂和凝视之后。或者我只是个新手!我希望OP不必走这种将序列合并到数据帧的路线,这看起来很尴尬。