1

我有一个数据框,它有两种 dtype:对象(期望字符串)和日期时间(期望日期时间)。我不明白这种行为以及它为什么会影响我的 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'),但仍然没有。你能告诉我要找什么吗?非常感谢。

在此处输入图像描述

4

1 回答 1

1

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

for col in sample.select_dtypes(include='object').columns:
    sample[col] = sample[col].str.strip().str.lower().fillna('NULL')
于 2018-11-24T17:30:45.183 回答