python - 如何替换DataFrame中的缺失数据
问题描述
假设我有以下数据框:
df = pd.DataFrame({'col1': [241, 123, 423], 'col2':[977, 78, np.NaN], 'col3':[76, 432, np.NaN], 'col4':[234, 321, 987]}, index=pd.date_range('2019-1-1', periods=3, freq="D")).rename_axis('Date')
输出:
col1 col2 col3 col4
Date
2019-01-01 241 977.0 76.0 234
2019-01-02 123 78.0 432.0 321
2019-01-03 423 NaN NaN 987
另一个数据框,甚至是一个系列,缺少col2
和的值col3
。如何NaN
用来自的值替换这些值df2
?
df2 = pd.DataFrame({'col2': 111, 'col3': 222}, index=[pd.to_datetime('2019-1-3')]).rename_axis('Date')
看起来像:
col2 col3
Date
2019-01-03 111 222
我想要的最终 DataFrame 应该是这样的:
col1 col2 col3 col4
Date
2019-01-01 241 977.0 76.0 234
2019-01-02 123 78.0 432.0 321
2019-01-03 423 111 222 987
解决方案
我们可以使用DataFrame.fillna
:
df=df.fillna(df2)
print(df)
col1 col2 col3 col4
Date
2019-01-01 241 977.0 76.0 234
2019-01-02 123 78.0 432.0 321
2019-01-03 423 111.0 222.0 987
如果你有一个按列排列的系列,就像用我们获得的那样,df2.iloc[0]
我们也可以这样做:
my_serie=df2.iloc[0]
print(my_serie)
col2 111
col3 222
Name: 2019-01-03 00:00:00, dtype: int64
print(df.fillna(my_serie))
col1 col2 col3 col4
Date
2019-01-01 241 977.0 76.0 234
2019-01-02 123 78.0 432.0 321
2019-01-03 423 111.0 222.0 987
推荐阅读
- javascript - ActiveSupport::MessageVerifier::InvalidSignature
- sql - 在选择 sqloracle 中展开 *
- typescript - 如何定义字符串类型的任何属性不包括某些属性
- python-3.x - 熊猫合并意外产生后缀
- javascript - 使用 react.js 从文件数组中删除文件
- symfony - Symfony 路由,单独的路由设置和忽略 _locale 前缀?
- yaml - 解析传递给 YML 的变量
- linux - 将物理 USB 端口关联到设备
- android - 如何在 junit 测试的 xml 报告中添加属性?
- c# - 活动的测试运行已中止。System.Reflection.TargetInvocationException