在 pandas 中选择 datetime64 列并将该列作为系列返回

问题描述 投票:0回答:0

给定的数据框:


import pandas as pd

# create a range of dates
dates = pd.date_range('2015-01-25', periods=5, freq='W')

# create a dataframe with the dates and an additional numeric column
dataframe = pd.DataFrame({
    'Date': dates,
    'Value': [10, 20, 30, 40, 50]
})

# print the dataframe
print(dataframe)

想要选择一个返回系列的列

dataframe['Date'] = pd.to_datetime(dataframe['Date'])
print(dataframe['Date'])
Returns: 'pandas.core.series.Series'>
0     2015-01-25
1     2015-02-01
2     2015-02-08
3     2015-02-15
4     2015-02-22
         ...    
161   2018-02-25
162   2018-03-04
163   2018-03-11
164   2018-03-18
165   2018-03-25

这行得通,但我想要其他方式(不提及列名称)

date_cols = dataframe.loc[:, dataframe.dtypes == 'datetime64[ns]']
print(date_cols)

这个输出:

          Date
0   2015-01-25
1   2015-02-01
2   2015-02-08
3   2015-02-15
4   2015-02-22
..         ...
161 2018-02-25
162 2018-03-04
163 2018-03-11
164 2018-03-18
165 2018-03-25

这会返回一个类对象,但我希望它作为 pandas 系列作为最后一个像 'pandas.core.series.Series' 。这真的可能吗?

提前致谢!

python pandas dataframe
© www.soinside.com 2019 - 2024. All rights reserved.