python - Pandas 不会就地 fillna()

标签 python pandas dataframe

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

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

假设我们只想为 xy 填充 fillna 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(dict.fromkeys(['x', 'y'], 0), inplace=True) # also works

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

相关文章:

python - 在 matplotlib 中调整/拉伸(stretch) 2d 直方图的大小与 x-y 相关的箱数?

Python Pandas 在中心指示器后去除字母 "|"

python - 如何在 ipython 笔记本中将 matplotlib 图抓取为 html?

python - 如何将数据保存到 csv Cantera 和错误 <cantera.composite.SolutionArray object at 0x7f4badca0fd0>

python - 如何使用 Pandas df 在 Python 中水平旋转 csv 表格?

python - 如何使用非分隔符 Pandas 将索引拆分为多索引

Python 和大数据。 user_agents 的替代方案(对于大数据集来说工作速度非常慢)?

python - 与 Pandas 的音量叠加

python 2.7 : difference between exit() and raise ValueError ("example")

r - 将“by”对象转换为R中的数据帧