首页 > 解决方案 > Pandas 在使用 .loc 过滤的数据帧上使用 .str

问题描述

我正在尝试float(64)date_of_birth名为drugs_tall. date_of_birth包含一些NA.

这是我最初的想法:

drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']] = drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']].astype('int').astype('str').str.zfill(6)

但是,这会产生错误

AttributeError: 'DataFrame' object has no attribute 'str'

我通过简单地解决这个问题(这个工作):

drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']] = drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']].astype('int').astype('str')

drugs_tall['date_of_birth'] = drugs_tall['date_of_birth'].str.zfill(6)

请注意,无法直接访问:

drugs_tall['date_of_birth'] = drugs_tall['date_of_birth'].str.zfill(6)

因为这会产生错误:

AttributeError: Can only use .str accessor with string values, which use 
np.object_ dtype in pandas

如果不使用 .loc 选择,也无法更改数据类型:

drugs_tall['date_of_birth'].astype('int').astype('str')

因为这将给出:

ValueError: Cannot convert non-finite values (NA or inf) to integer

我是以一种奇怪的方式解决这个问题还是误解了数据框的工作原理?我知道我的两线解决方案相当简短,但我不明白是什么让两线解决方案与我最初的想法不同。

谢谢

标签: pythonpython-3.xpandasdataframe

解决方案


您的列索引器应该是一个标量'dob'而不是一个列表['dob']。这就是为什么您会找到一个数据框作为索引操作的输出。这是有道理的:一个列序列被解释为一个数据框,一个标量列给出一个序列。

对于您的任务,您可以pd.Series.notnullpd.DataFrame.loc. 如果 Pandas 将您的值存储为float.

df = pd.DataFrame({'dob': [np.nan, None, 11585, 52590]})

mask = df['dob'].notnull()
df.loc[mask, 'dob'] = df.loc[mask, 'dob'].astype(int).astype(str).str.zfill(6)

print(df)

      dob
0     NaN
1     NaN
2  011585
3  052590

推荐阅读