对列值进行排序

2024-05-12 13:13:40 发布

您现在位置:Python中文网/ 问答频道 /正文

(工业工程)

        count
2015-01  2
2015-02  1
2015-03  4

我试过的那群人pd.groupby公司(b,by=[b。索引.月,b。索引。年份])你知道吗

但对象没有属性'month'错误


Tags: 对象by属性count错误公司工程pd
1条回答
网友
1楼 · 发布于 2024-05-12 13:13:40

应用sorted,将key参数设置为pd.to_datetime

df.assign(date=df.date.apply(sorted, key=pd.to_datetime))

  id                                  date
0  a              [2015-02-01, 2015-03-01]
1  b                          [2015-03-01]
2  s              [2015-01-01, 2015-03-01]
3  f  [2015-01-01, 2015-01-01, 2015-03-01]

然后使用pd.value_counts

pd.value_counts(pd.to_datetime(df.date.sum()).strftime('%Y-%m'))

2015-03    4
2015-01    3
2015-02    1
dtype: int64

调试

你应该能够复制和粘贴这个代码。。。请验证它是否按预期运行。你知道吗

import pandas as pd

df = pd.DataFrame(dict(
        id=list('absf'),
        date=[
            ['2015-03-01', '2015-02-01'],
            ['2015-03-01'],
            ['2015-01-01', '2015-03-01'],
            ['2015-01-01', '2015-01-01', '2015-03-01']
        ]
    ))[['id', 'date']]

print(df.assign(date=df.date.apply(sorted, key=pd.to_datetime)))
print()
print(pd.value_counts(pd.to_datetime(df.date.sum()).strftime('%Y-%m')))

你应该期待看到

  id                                  date
0  a              [2015-02-01, 2015-03-01]
1  b                          [2015-03-01]
2  s              [2015-01-01, 2015-03-01]
3  f  [2015-01-01, 2015-01-01, 2015-03-01]

2015-03    4
2015-01    3
2015-02    1
dtype: int64

相关问题 更多 >