python - 如何对熊猫中的列进行分组?
问题描述
我有这样的DataFrame:
Jan Feb Jan.01 Feb.01
0 0 4 6 4
1 2 5 7 8
2 3 6 7 7
如何将其分组以获得此结果?我必须使用哪些功能?
2000 2001
Jan Feb Jan.01 Feb.01
0 0 4 6 4
1 2 5 7 8
2 3 6 7 7
解决方案
我认为这会做
df
Jan Feb Jan.01 Feb.01
0 2016-01-01 00:00:00 2016-01-02 00:00:00 2 413
1 2016-01-02 01:00:00 2016-01-03 01:00:00 1 414
2 2016-01-03 02:00:00 2016-01-04 02:00:00 2 763
3 2016-01-04 03:00:00 2016-01-05 03:00:00 1 837
4 2016-01-05 04:00:00 2016-01-06 04:00:00 2 375
level1_col = pd.Series(df.columns).str.split('.').apply(lambda x: 2000+int(x[1]) if len(x) == 2 else 2000)
level2_col = df.columns.tolist()
df.columns = [level1_col, level2_col]
df
2000 2001
Jan Feb Jan.01 Feb.01
0 2016-01-01 00:00:00 2016-01-02 00:00:00 2 413
1 2016-01-02 01:00:00 2016-01-03 01:00:00 1 414
2 2016-01-03 02:00:00 2016-01-04 02:00:00 2 763
3 2016-01-04 03:00:00 2016-01-05 03:00:00 1 837
4 2016-01-05 04:00:00 2016-01-06 04:00:00 2 375
df[2000]
Jan Feb
0 2016-01-01 00:00:00 2016-01-02 00:00:00
1 2016-01-02 01:00:00 2016-01-03 01:00:00
2 2016-01-03 02:00:00 2016-01-04 02:00:00
3 2016-01-04 03:00:00 2016-01-05 03:00:00
4 2016-01-05 04:00:00 2016-01-06 04:00:00
推荐阅读
- android - Android/Xamarin Forms:为什么 OnActivityResult 没有为我的相机意图触发?
- r - 无法使用外部 tikz 文件编译 Rmd 文件
- rest - Codeigniter 会话不适用于 PHP 7.3.0
- python-3.x - 使用 Python 3 字符串格式化语法登录 Python
- python-3.x - 如何使边框与子标题对齐?
- c - 如果 != 0 则返回函数结果的 C 宏
- asp.net - 使用 Dapper 在数据库中执行动态实体
- json - 在 Laravel 刀片文件中,数据未打印但为 json 格式,数据存在
- sql - 节点 js SQL 事务 REST
- google-bigquery - bigquery 蒸汽缓冲区持续多长时间