python - 如何用其他系列替换 Pandas 数据框的子集

标签 python pandas data-analysis missing-data

我认为这是一个微不足道的问题,但我无法让它发挥作用。

d = {   'one': pd.Series([1,2,3,4], index=['a', 'b', 'c', 'd']),
            'two': pd.Series([np.nan,6,np.nan,8], index=['a', 'b', 'c', 'd']),
            'three': pd.Series([10,20,30,np.nan], index = ['a', 'b', 'c', 'd'])}         
   ​    
df = pd.DataFrame(d)
df

    one     three   two
a   1       10.0    NaN
b   2       20.0    6.0
c   3       30.0    NaN
d   4       NaN     8.0

我的系列:

​fill = pd.Series([30,60])

我想替换一个特定的列,让它成为“二”。在我的名为 fill 的系列中,“二”列满足条件:是 Nan。你能帮我吗? 我想要的结果:

df

    one     three   two
a   1       10.0    30
b   2       20.0    6.0
c   3       30.0    60
d   4       NaN     8.0

最佳答案

我想你需要 locisnull用于替换从 fill 创建的 numpy array by Series.values :

df.loc[df.two.isnull(), 'two'] = fill.values
print (df)
   one  three   two
a    1   10.0  30.0
b    2   20.0   6.0
c    3   30.0  60.0
d    4    NaN   8.0

关于python - 如何用其他系列替换 Pandas 数据框的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42187655/

相关文章:

python - 如何用这些函数创建字典的字典?

python - 如何使用列表替换文本文件中的列?

Python - 使用 Ipyvolume 库在 x、y 和 z 轴上绘制不同颜色的问题

python - 导入 GDK 的问题

python - 捕获多处理池映射中的错误

Python 数据帧复制

python - 使用 reduce 选项更改数据类型的 Pandas 调用适用于空数据框

将矩阵中每个等于 0 的元素替换为上一行的相应元素

python - 用python进行傅立叶变换

python - Torch7 Mac安装报错