【问题标题】:How to extract date form data frame column?如何从数据框列中提取日期?
【发布时间】:2016-09-27 11:06:11
【问题描述】:

我有这样的数据框:

    month       items
0   1962-01-01  589
1   1962-02-01  561
2   1962-03-01  640
3   1962-04-01  656
4   1962-05-01  723

我需要从此数据框中获取年份或月份并创建数组,但我不知道该怎么做。

预期结果:

years = [1962, 1962, 1962....]
monthes = [1, 2, 3, 4, 5.....]

你能帮帮我吗?

【问题讨论】:

  • 抱歉这是pandas?如果月份列是 dtype datetime 那么你可以只做 years = df['month'].dt.year.tolist()months = df['month'].dt.month.tolist()

标签: python python-2.7 pandas dataframe


【解决方案1】:

假设这是pandas,您可能需要将月份列转换为dtype datetime,然后您可以使用.dt 访问器获取年份和月份属性:

In [33]:
df['month'] = pd.to_datetime(df['month'])
df.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 2 columns):
month    5 non-null datetime64[ns]
items    5 non-null int64
dtypes: datetime64[ns](1), int64(1)
memory usage: 120.0 bytes

In [35]:
years = df['month'].dt.year.tolist()
months = df['month'].dt.month.tolist()
print(years)
print(months)

[1962, 1962, 1962, 1962, 1962]
[1, 2, 3, 4, 5]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-23
    • 1970-01-01
    • 2023-01-26
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    相关资源
    最近更新 更多