python - 将具有重复值的列移动到单行 Pandas
问题描述
这是我的数据:
Identification Req
RCFD1797 Violet
BHCKK085 Green
RCFD1797 Green
BHCKK085 Orange
RCFD1797 Blue
BHCKK085 Yellow
BHCKK085 Red
WRSS1797 Green
WRSS1797 Violet
WRSS1797 Blue
RCON1797 Violet
RCON1797 Green
RCON1797 Blue
RCON1797 Indigo
BHDM1797 Violet
BHDM1797 Green
BHDM1797 Blue
BHDM1797 Indigo
第一列用重复的 ID 号填充。例如,“RCFD1797”出现了 3 次,每行有一个要求。这就是我需要它的样子:
Identification Req_1 Req_2 Req_3 Req_4
RCFD1797 Violet Green Blue
BHCKK085 Green Orange Yellow Red
WRSS1797 Green Violet Blue
RCON1797 Violet Green Blue Indigo
BHDM1797 Violet Green Blue Indigo
我使用 Pandas 导入我的 Excel 文件没有问题,但我不知道如何定义我的数据框以生成上面的第二个表。有任何想法吗?
谢谢!
解决方案
试试这个:
test
#Pasting only the partial table here
Identification Req
0 RCFD1797 Violet
1 BHCKK085 Green
2 RCFD1797 Green
3 BHCKK085 Orange
4 RCFD1797 Blue
5 BHCKK085 Yellow
6 BHCKK085 Red
.. ... ...
my_df = test.groupby('Identification')['Req'].apply(list).apply(pd.Series)
my_df.columns = ['Req'+str(i) for i in my_df.columns]
my_df
Req0 Req1 Req2 Req3
Identification
BHCKK085 Green Orange Yellow Red
BHDM1797 Violet Green Blue Indigo
RCFD1797 Violet Green Blue NaN
RCON1797 Violet Green Blue Indigo
WRSS1797 Green Violet Blue NaN
希望这可以帮助。
推荐阅读
- java - 无法编译的源代码 - 表达式的非法开始
- shell - 用于提取正在运行的 sid 的 shell 脚本
- javascript - 如何在 JS 模块中定义错误类
- android - 长按像paytm和swiggy这样的Android应用程序图标后如何显示菜单选项?
- python - Keras 模型 evaluate() 和 predict_classes() 给出了相互矛盾的结果
- reactjs - 在 React 中清除 Apollo GraphQL 客户端中的特定查询缓存
- r - 在 R 中,我们如何将表拆分为由第一列和其余每一列组成的多个数据帧?
- ios - 是否可以使用 avspeechsynthesizer 保存音频?
- reactjs - 如何使用console.log在react mobx中评估可观察或计算数组
- php - 使用 PHP 的带有 Bootstrap/Jquery 的 HTML 电子邮件