即)
count
2015-01 2
2015-02 1
2015-03 4
对于我尝试过的组 pd.groupby(b,by=[b.index.month,b.index.year])
但存在对象没有属性“月份”错误
最佳答案
应用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
关于python - pandas 对列值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43479931/