python - 使用 pandas 中其他两列的值从分类变量中创建列
问题描述
原始数据框
我希望它转换为以下结构:
Area |Ind3_2016|Ind6_2016|...|Ind12_2016|Ind3_2017|Ind6_2017|...| Ind12_2017
-------|---------|---------|---|----------|---------|---------|---|-----------
Alabama| 2306 | 2270 |...| 35621 | 2409 | 3391 |...| 36397
根据 2016 年和 2017 年 IndCode 列中的每个唯一值创建列,并将 2016 年和 2017 年列的值放在这些列下。
解决方案
您可以执行两个单独的枢轴然后连接结果,或者预先进行一些堆叠并只做一个枢轴。
样本数据
import pandas as pd
df = pd.DataFrame({'Area': ['A', 'A','A','A','A'],
'IndCode': [3, 6, 10, 11, 12],
'Industry': ['blah', 'foo', 'bar', 'baz', 'boo'],
'2016': [2306, 2270, 5513, 7730, 35621],
'2017': [2409, 3391, 5438, 7890, 36397]
})
两个枢轴+ Concat
pd.concat([pd.pivot_table(df, index='Area', columns='Ind'+df.IndCode.astype(str)+'_2016', values='2016'),
pd.pivot_table(df, index='Area', columns='Ind'+df.IndCode.astype(str)+'_2017', values='2017')],axis=1)
输出:
IndCode Ind10_2016 Ind11_2016 Ind12_2016 Ind3_2016 Ind6_2016 Ind10_2017 Ind11_2017 Ind12_2017 Ind3_2017 Ind6_2017
Area
A 5513 7730 35621 2306 2270 5438 7890 36397 2409 3391
枢轴前堆叠
df2 = df.set_index(['Area', 'IndCode'])[['2016', '2017']].stack().reset_index()
pd.pivot_table(df2, index='Area',
columns='Ind'+df2.IndCode.astype('str')+'_'+df2.level_2.astype(str),
values=0).reset_index()
输出:
Area Ind10_2016 Ind10_2017 Ind11_2016 Ind11_2017 Ind12_2016 Ind12_2017 Ind3_2016 Ind3_2017 Ind6_2016 Ind6_2017
0 A 5513 5438 7730 7890 35621 36397 2306 2409 2270 3391
推荐阅读
- python - 从数据框python创建自定义字典时出现字符串索引错误
- listview - 如何同步单子滚动视图和列表视图颤动的滚动?
- javascript - 如何按其共同值之一对每个级别的 json 数据进行分组
- java - Spring boot rest api更新列
- node.js - 如何使用formdata在react-redux中发布图像并发送到nodejs
- r - 如何以升序或降序重新排列因子的水平?
- angularjs - Angularjs 与 ASP.Net 核心设计
- android - CrashlyticsCore:发送报告 com.crashlytics.android.core.SessionReport@ 时发生错误
- c++ - 如果分配该数组引发异常,您是否应该释放该数组?
- go - 可以用grpc传输context的内容吗?