python - 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
我是以一种奇怪的方式解决这个问题还是误解了数据框的工作原理?我知道我的两线解决方案相当简短,但我不明白是什么让两线解决方案与我最初的想法不同。
谢谢
解决方案
您的列索引器应该是一个标量'dob'
而不是一个列表['dob']
。这就是为什么您会找到一个数据框作为索引操作的输出。这是有道理的:一个列序列被解释为一个数据框,一个标量列给出一个序列。
对于您的任务,您可以pd.Series.notnull
与pd.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
推荐阅读
- maven - Maven:如何在构建和发布期间跳过安装/部署快速入门或示例模块?
- javascript - Vuejs fusioncharts 具有完全透明的背景
- angularjs - 为什么 $invalid、$valid、$dirty 在 Visual Studio 的 AngularJS 项目中不起作用?
- python-jedi - jedi infer() 不适用于我的基于 AWS S3 的自定义 Python 导入器
- flutter - 如何在不更新的情况下在已发布的 Flutter 应用中添加新项目
- c++ - 如何使用 libclang 处理 if init 语句(c++17)
- django - 使用 django tables2 和 django_filters 时如何过滤连接的值
- google-api - 谷歌日历 API 配额:千人使用一个谷歌账户
- azure - 应用自定义域后,Azure 上的 Web 应用加载缓慢
- c++ - 使用 snappy 获取未定义的引用错误