简体   繁体   English

Pandas fillna() 不将一列中的值应用到整个 dataframe

[英]Pandas fillna() does not apply values from one column to an entire dataframe

Please explain, why this won't work (hc is pandas dataframe on below example):请解释为什么这不起作用(hc 在下面的例子中是 pandas dataframe):

import pandas as pd
import numpy as np

hc = pd.DataFrame([['Adolf', np.nan],
                  ['Hans', 'Johan']],
                  columns=('First Name', 'Second Name'))

hc.fillna(value=hc["First Name"])
 First Name Second Name 0 Adolf NaN 1 Hans Johan
hc[['First Name','Second Name']].fillna(value=hc["First Name"])
 First Name Second Name 0 Adolf NaN 1 Hans Johan

Using other column's value works only for one column like that:使用其他列的值仅适用于这样的一列:

hc['Second Name'].fillna(value=hc["First Name"],inplace=True)
hc
 First Name Second Name 0 Adolf Adolf 1 Hans Johan

I wish to apply a value (mask value) from one column to NaN-s in the entire dataframe.我希望将一列中的值(掩码值)应用于整个 dataframe 中的 NaN-s。

IIUC, you want to fillna with a Series as reference, per row. fillna ,您想在每行中填充一个系列作为参考。

hc = hc.fillna(hc['First Name'])

This is not currently supported on the columns for all pandas version (it is in the latest), but you can cheat using a double transpose to perform the operation on the rows:目前不支持所有 pandas 版本(最新版本)的列,但您可以使用双转置作弊以对行执行操作:

hc = hc.T.fillna(hc['First Name']).T

output: output:

  First Name Second Name
0      Adolf       Adolf
1       Hans       Johan

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM