gpt4 book ai didi

python - 根据索引值用系列填充多个缺失值

转载 作者:太空宇宙 更新时间:2023-11-03 12:56:17 25 4
gpt4 key购买 nike

考虑pd.DataFrame df

df = pd.DataFrame([
[np.nan, 1, np.nan],
[2, np.nan, np.nan],
[np.nan, np.nan, 3 ],
], list('abc'), list('xyz'))

df

enter image description here

pd.Series s

s = pd.Series([10, 20, 30], list('abc'))

如何根据s的索引和df

例如:

  • df.loc['c', 'x']NaN
  • s.loc['c']30

预期结果
enter image description here

最佳答案

pandas 按列处理此问题,没有任何问题。假设我们有不同的 s

s = pd.Series([10, 20, 30], ['x', 'y', 'z'])

那么我们可以

df.fillna(s)

x y z
a 10.0 1.0 30.0
b 2.0 20.0 30.0
c 10.0 20.0 3.0

但这不是你想要的。使用你的 s

s = pd.Series([10, 20, 30], ['a', 'b', 'c'])

然后 df.fillna(s) 什么都不做。但我们知道它适用于列,所以:

df.T.fillna(s).T

x y z
a 10.0 1.0 10.0
b 2.0 20.0 20.0
c 30.0 30.0 3.0

关于python - 根据索引值用系列填充多个缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40470620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com