根据数据类型获取 pandas 数据框列的列表 [英] get list of pandas dataframe columns based on data type

查看:84
本文介绍了根据数据类型获取 pandas 数据框列的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的数据框包含以下列:

If I have a dataframe with the following columns:

1. NAME                                     object
2. On_Time                                      object
3. On_Budget                                    object
4. %actual_hr                                  float64
5. Baseline Start Date                  datetime64[ns]
6. Forecast Start Date                  datetime64[ns] 

我想说:这是一个数据框,请给我列出对象类型或日期时间类型的列的列表吗?

I would like to be able to say: here is a dataframe, give me a list of the columns which are of type Object or of type DateTime?

我有一个将数字(Float64)转换为两位小数的函数,我想使用特定类型的数据框列的列表,并通过该函数运行它以将它们全部转换为2dp.

I have a function which converts numbers (Float64) to two decimal places, and I would like to use this list of dataframe columns, of a particular type, and run it through this function to convert them all to 2dp.

也许:

For c in col_list: if c.dtype = "Something"
list[]
List.append(c)?

推荐答案

如果您想要某种类型的列的列表,可以使用groupby:

If you want a list of columns of a certain type, you can use groupby:

>>> df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
>>> df
   A       B  C  D   E
0  1  2.3456  c  d  78

[1 rows x 5 columns]
>>> df.dtypes
A      int64
B    float64
C     object
D     object
E      int64
dtype: object
>>> g = df.columns.to_series().groupby(df.dtypes).groups
>>> g
{dtype('int64'): ['A', 'E'], dtype('float64'): ['B'], dtype('O'): ['C', 'D']}
>>> {k.name: v for k, v in g.items()}
{'object': ['C', 'D'], 'int64': ['A', 'E'], 'float64': ['B']}

这篇关于根据数据类型获取 pandas 数据框列的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆