pandas 使用熊猫获取所有日期时间类型的列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42322950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get all columns with datetime type using pandas?
提问by J. Doe
I have a huge DataFrame where the columns aren't ever in order nor do I know their name.
我有一个巨大的 DataFrame,其中的列从来没有按顺序排列过,我也不知道它们的名字。
What do I do to find all the columns which are datetime types?
我该怎么做才能找到所有日期时间类型的列?
Most of the solutions online, the poster knows the name of the column so I am having a bit trouble as I do not. What can I do in this situation?
网上的大多数解决方案,发帖人都知道专栏的名称,所以我有点麻烦,因为我不知道。在这种情况下我能做什么?
回答by miradulo
You can use pandas.DataFrame.select_dtypes()
, and include only the datetime64 type.
您可以使用pandas.DataFrame.select_dtypes()
, 并且仅包含 datetime64 类型。
df.select_dtypes(include=['datetime64'])
Demo
演示
>>> df
dts1 dts2 ints
0 2012-01-01 2004-01-01 0
1 2012-01-02 2004-01-02 1
2 2012-01-03 2004-01-03 2
.. ... ... ...
97 2012-04-07 2004-04-07 97
98 2012-04-08 2004-04-08 98
99 2012-04-09 2004-04-09 99
>>> df.select_dtypes(include=['datetime64'])
dts1 dts2
0 2012-01-01 2004-01-01
1 2012-01-02 2004-01-02
2 2012-01-03 2004-01-03
.. ... ...
97 2012-04-07 2004-04-07
98 2012-04-08 2004-04-08
99 2012-04-09 2004-04-09
回答by Parfait
Since each column of a pandas DataFrame is a pandas Series simply iterate through list of column names and conditionally check for series.dtype
of datetime (typically datetime64[ns]):
由于 Pandas DataFrame 的每一列都是一个 Pandas 系列,因此只需遍历列名列表并有条件地检查series.dtype
日期时间(通常为datetime64[ns]):
for col in df.columns:
if df[col].dtype == 'datetime64[ns]':
print(col)
Or as list comprehension:
或者作为列表理解:
[col for col in df.columns if df[col].dtype == 'datetime64[ns]']
Or as a series filter:
或作为串联过滤器:
df.dtypes[df.dtypes=='datetime64[ns]']