python - 如何在 Python Pandas Dataframe 中过滤混合数据类型对象中的字符串值

标签 python pandas dataframe

我在 Pandas Dataframe 中有一列,例如:(其 value_counts 如下所示)

1                      246804
2                      135272
5                        8983
8                        3459
4                        3177
6                        1278
9                         522
D                         314
E                          91
0                          29
F                          20    
Name: Admission_Source_Code, dtype: int64

如您所见,它包含整数和字母。我必须编写一个函数,我必须在其中过滤和搜索带字母的值。

我最初使用 pd.read_excel 导入此数据集,但在阅读了多个错误报告后,似乎 read_excel 没有选项可以将列显式读取为字符串。

所以我尝试使用具有 dtype 选项的 pd.read_csv 进行阅读。最初此列默认存储为 float64,现在即使我尝试运行

Df_name['Admission_Source_Code'] = Df_name['Admission_Source_Code'].astype(int).astype('str')

我无法将其格式化为字符串列。

因此,当我过滤

Accepted[Accepted['Admission_Source_Code']==1]

它有效,但是

Accepted[Accepted['Admission_Source_Code']=='E']

仍然没有返回结果。当我尝试在掩码中说 str(column_name) 时,它说无效文字。 有人可以帮助我了解如何更改 dtype 或如何过滤字母值吗?

谢谢。

附言即使格式化为对象也无济于事

最佳答案

我认为您应该能够使用 .loc[] 索引器过滤您的 value_counts 系列,按字符串过滤(索引)

演示:

In [27]: df
Out[27]:
                        Count
Admission_Source_Code
1                      246804
2                      135272
5                        8983
8                        3459
4                        3177
6                        1278
9                         522
D                         314
E                          91
0                          29
F                          20

In [28]: df.index.dtype
Out[28]: dtype('O')

In [29]: df.loc['2']
Out[29]:
Count    135272
Name: 2, dtype: int64

In [30]: df.loc[['2','E','5','D']]
Out[30]:
                        Count
Admission_Source_Code
2                      135272
E                          91
5                        8983
D                         314

列出索引值:

In [36]: df.index.values
Out[36]: array(['1', '2', '5', '8', '4', '6', '9', 'D', 'E', '0', 'F'], dtype=object)

更新: 从 Pandas 0.20.1 开始 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers .

关于python - 如何在 Python Pandas Dataframe 中过滤混合数据类型对象中的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39711977/

相关文章:

Python - 字符替换的迭代

python - 检查字典列表中的值时将 for 循环转换为 all()

python - 应用适用于除最后一行以外的所有行的函数

python - 如何根据多个条件用字符串拆分 Pandas 数据框列

R DataFrame - 包含多个术语的列的一种热编码

r - 在 R 中创建许多新的数据框

python - 通过Python添加Microsoft Face API的本地路径

python - 如何编译用于 Python 的 Fortran 库? (f2py 可能不是一个选项)

python - 对 Pandas 中的每隔一行进行子集化?

Python:向 pandas 数据框添加一列