python - 相同列名的数据透视表 - 必须在数据透视后重复
问题描述
我有如下数据
user region attribute reading
Jon Europe fathername peter
Jon Europe age 50
Jon Europe mothername mary
Jon Europe age 44
Jon Europe brothername duke
Jon Europe age 25
这就是它在sql数据库中的存储方式。我正在将其读入数据框并尝试生成如下数据
attribute fathername age mothername age brothername age
User region
Don Europe peter 50 mary 44 duke 25
但是,我无法得到这个
年龄不重复,只出现一次,取其中任何一个值
这是我尝试过的 -
pd.pivot_table(df_mysql , index=['User'],columns=['attribute'],values=['reading'], aggfunc=lambda x: x,dropna = 'False')
必须出现重复的属性(列)。请问我对此有什么想法吗
解决方案
首先在 pandas 中最好避免重复的列名,因此可能的解决方案是使用以下方法删除重复值pivot
:
print (df)
user region attribute reading
0 Jon Europe fathername peter
1 Jon Europe age 50
2 Jon Europe mothername mary
3 Jon Europe age 44
4 Jon Europe brothername duke
5 Jon Europe age 25
6 Jon1 Europe fathername peter
7 Jon1 Europe age 50
8 Jon1 Europe mothername mary
9 Jon1 Europe age 44
10 Jon1 Europe brothername duke
11 Jon1 Europe age 25
m = df.duplicated(['user','region', 'attribute'], keep=False)
df.loc[m, 'attribute'] += df[m].groupby(['user','region', 'attribute']).cumcount().astype(str)
df = df.pivot_table(index=['user','region'],
columns='attribute',
values='reading',
aggfunc='sum').reindex(df['attribute'].unique(), axis=1)
print (df)
attribute fathername age0 mothername age1 brothername age2
user region
Jon Europe peter 50 mary 44 duke 25
Jon1 Europe peter 50 mary 44 duke 25
推荐阅读
- reactjs - React-select onchange 事件多重属性
- javascript - JS如何添加而不是连接数字
- flutter - StatefulWidget 中的布局更改后的“'_listenerAttached': is not true”
- c# - c#在转换之前检测字符串是长还是DateTime
- javascript - 如何通过单击按钮将文本复制到剪贴板
- macos - 围攻 - HTTPS 需要 libssl - MacOS Mojave
- r - 如何在使用 R 中的“nleqslv”包求解非线性方程时施加约束
- xslt - XSLT 将样式从 3.0 转换为 2.0 - 变量引用错误
- java - Spring @PropertySource 在 PREVIOUS 文件夹中查找属性文件
- android - FileProvider 如何在 provider_path.xml 中选择/区分提供者路径?