- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给 Pandas df
具有不同的数据类型,df.select_dtypes
对于仅保留所需的列或删除特定应用程序不需要的列非常有用。
但是,似乎没有办法寻址 string
使用此方法的数据类型。
来自the docs (强调我的):
ValueError
If both of include and exclude are empty
If include and exclude have overlapping elements
If any kind of string dtype is passed in.
和
To select strings you must use the object dtype, but note that this will return all object dtype columns
确实,使用df.select_dtypes(exclude=['str'])
引发错误(尽管它是 TypeError
而不是文档声称的 ValueError
)并使用 df.select_dtypes(exclude=['object'])
删除所有 object
列,而不仅仅是 string
列。
给定 df
像这样:
df = pd.DataFrame({'int_col':[0,1,2,3,4],
'dict_col':[dict() for i in range(5)],
'str_col':list('abcde')})
并考虑到
df.dtypes
是 object
对于两者str_col
和dict_col
:
排除或包含所有字符串列的最佳方法是什么?
最佳答案
选项 1
使用df.applymap
和type
,并等同于str
:
In [377]: (df.applymap(type) == str).all(0)
Out[377]:
dict_col False
int_col False
str_col True
dtype: bool
每列中的每个元素都转换为其类型,然后等于 str
。之后,只需调用 .all(0)
或 .min(0)
即可获得每列的判决。
选项 2
使用df.applymap
和isinstance
:
In [342]: df.applymap(lambda x: isinstance(x, str)).all(0)
Out[342]:
dict_col False
int_col False
str_col True
<小时/>
要包含这些字符串列,您可以对列进行 bool 索引:
idx = ... # one of the two methods above
df_new = df[df.columns[idx]]
排除
df_new = df[df.columns[~idx]]
关于python - 选择 pandas df 中的字符串列(相当于 df.select_dtypes),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45836794/
我有几列既有 float 又有字符串。我希望能够选择这些列并根据它们的数据类型应用不同的掩码。 我找到了 select_dtypes() 方法,但它运行在整个数据帧上,我需要的是能够进行列选择。例如:
import pandas as pd import numpy as np test_df = pd.DataFrame([[1,2]]*4, columns=['x','y'])
目标:以与 Pandas 类似的方式使用 NumPy 和“select_dtypes”。 设置如下数据框: >>> df = pd.DataFrame({'a': [1, 2] * 3, ...
如果在“search”列中找到字符串“something”,这两种删除行的方法有什么区别? 第一种方法: mydata = mydata.set_index("search") mydata = my
为什么这个测试代码是预期的行为: test = pd.DataFrame({'bool' :[False, True], 'int':[-1,2], 'float': [-2.5, 3.4],
给 Pandas df具有不同的数据类型,df.select_dtypes对于仅保留所需的列或删除特定应用程序不需要的列非常有用。 但是,似乎没有办法寻址 string使用此方法的数据类型。 来自th
我是一名优秀的程序员,十分优秀!