pandas排序列值

时间:2017-04-18 18:44:36

标签: python pandas dataframe

IE)

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

我尝试了pd.groupby(b,by = [b.index.month,b.index.year])

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

1 个答案:

答案 0 :(得分:1)

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