我正在尝试在数据框中的 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
假设我们只想为 x
和 y
填充 fillna
,不 a
和b
。
我希望使用 .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/