python - Pandas 不会 fillna() 到位

标签 python pandas dataframe

我正在尝试在字符串/对象类型的数据框中的 4 个特定列上用“”填充 NA。我可以在 fillna() 时将这些列分配给一个新变量,但是当我 fillna() inplace 时,基础数据不会改变。

a_n6 = a_n6[["PROV LAST", "PROV FIRST", "PROV MID", "SPEC NM"]].fillna("")
a_n6

给我:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1542 entries, 0 to 3611
Data columns (total 4 columns):
PROV LAST     1542  non-null values
PROV FIRST    1542  non-null values
PROV MID      1542  non-null values
SPEC NM       1542  non-null values
dtypes: object(4)

但是

a_n6[["PROV LAST", "PROV FIRST", "PROV MID", "SPEC NM"]].fillna("", inplace=True)
a_n6

给我:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1542 entries, 0 to 3611
Data columns (total 7 columns):
NPI           1103  non-null values
PIN           1542  non-null values
PROV FIRST    1541  non-null values
PROV LAST     1542  non-null values
PROV MID      1316  non-null values
SPEC NM       1541  non-null values
flag          439  non-null values
dtypes: float64(2), int64(1), object(4)

这只是一行,但仍然令人沮丧。我做错了什么?

最佳答案

使用 dict 作为 fillna()value 参数

正如@rhkarls 对@Jeff 的回答的评论中提到的,使用索引到列列表的 .loc 将不支持 inplace 操作,我也发现了这一点令人沮丧。这是一个解决方法。

例子:

import pandas as pd
import numpy as np

df = pd.DataFrame({'a':[1,2,3,4,np.nan],
                   'b':[6,7,8,np.nan,np.nan],
                   'x':[11,12,13,np.nan,np.nan],
                   'y':[16,np.nan,np.nan,19,np.nan]})
print(df)
#     a    b     x     y
#0  1.0  6.0  11.0  16.0
#1  2.0  7.0  12.0   NaN
#2  3.0  8.0  13.0   NaN
#3  4.0  NaN   NaN  19.0
#4  NaN  NaN   NaN   NaN

假设我们只想fillna xy不是 ab

我希望使用 .loc 可以工作(就像在作业中一样),但它没有,如前所述:

# doesn't work
df.loc[:,['x','y']].fillna(0, inplace=True)
print(df) # nothing changed

然而,documentation表示 fillna()value 参数可以是:

alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). (values not in the dict/Series/DataFrame will not be filled).

事实证明,使用值的字典是可行的:

# works
df.fillna({'x':0, 'y':0}, inplace=True)
print(df)
#     a    b     x     y
#0  1.0  6.0  11.0  16.0
#1  2.0  7.0  12.0   0.0
#2  3.0  8.0  13.0   0.0
#3  4.0  NaN   0.0  19.0
#4  NaN  NaN   0.0   0.0

此外,如果您的子集中有很多列,您可以使用字典理解,如:

df.fillna({x:0 for x in ['x','y']}, inplace=True) # also works

关于python - Pandas 不会 fillna() 到位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21998354/

相关文章:

python - 如何检查一列中的值是否等于另一列数据框中的值

python - 连接具有相同列名但后缀不同的数据框

python - 减小已保存视频的大小/分辨率

python - 转换为 Logn Python 3.7

python - 将日期转换为 float 以对 Pandas 数据框进行线性回归

python - 删除 pandas DF 列上的空格将 bool 值转换为 NaN

python - 全息 View 中仅出现 1 行图例

python - 将日期时间日期转换为字符串 Python Dataframe 时的SettingWithCopyWarning 消息

python - 将 DataFrame 列表保存到多表 Excel 电子表格

r - S4 类列表到数据框