gpt4 book ai didi

python - 选择 pandas df 中的字符串列(相当于 df.select_dtypes)

转载 作者:行者123 更新时间:2023-12-03 00:16:14 24 4
gpt4 key购买 nike

给 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_coldict_col :


排除或包含所有字符串列的最佳方法是什么?

最佳答案

选项 1

使用df.applymaptype,并等同于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.applymapisinstance:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com