pandas.Dataframe() 混合数据类型和奇怪的 .fillna() 行为

pandas.Dataframe() mixed data types and strange .fillna() behaviour

我有一个数据框,它有两个数据类型:对象(期望字符串)和日期时间(期望日期时间)。我不明白这种行为以及它为什么会影响我的 fillna()。

使用 inplace=True 调用 .fillna() 会擦除表示为 int64 的数据,尽管已使用 .astype(str)

在没有它的情况下调用 .fillna() 没有任何作用。

我知道 pandas / numpy dtypes 与 python 本机不同,但这是正确的行为还是我遇到了严重的错误?

示例:

import random
import numpy
sample = pd.DataFrame({'A': [random.choice(['aabb',np.nan,'bbcc','ccdd']) for x in range(15)],
                       'B': [random.choice(['2019-11-30','2020-06-30','2018-12-31','2019-03-31']) for x in range(15)]})
sample.loc[:, 'B'] = pd.to_datetime(sample['B'])

for col in sample.select_dtypes(include='object').columns.tolist():
    sample.loc[:, col].astype(str).apply(lambda x: str(x).strip().lower()).fillna('NULL')

for col in sample.columns:
    print(sample[col].value_counts().head(15))
    print('\n')

这里既没有出现'NULL'也没有出现'nan'。添加了 .replace('nan','NULL'),但仍然没有。你能告诉我要寻找什么吗?非常感谢。

这里的问题是将缺失值转换为 strings,因此 fillna 无法工作。解决方案是使用 pandas 函数 Series.str.strip and Series.str.lower 处理缺失值非常好:

for col in sample.select_dtypes(include='object').columns:
    sample[col] = sample[col].str.strip().str.lower().fillna('NULL')