[英]pandas.DataFrame: How to merge rows with a common column value in the same pandas.DataFrame
I have a pandas.DataFrame that looks like that:我有一个 pandas.DataFrame 看起来像这样:
index![]() |
projectid![]() |
question![]() |
answer![]() |
---|---|---|---|
0 ![]() |
1 ![]() |
'q1' ![]() |
'str1' ![]() |
1 ![]() |
1 ![]() |
'q2' ![]() |
'str2' ![]() |
2 ![]() |
1 ![]() |
'q3' ![]() |
'str3' ![]() |
3 ![]() |
2 ![]() |
'q1' ![]() |
'str4' ![]() |
4 ![]() |
2 ![]() |
'q3' ![]() |
'str6' ![]() |
And I would like to format it like that:我想像这样格式化它:
index![]() |
projectid![]() |
question1![]() |
answer1![]() |
question2![]() |
answer2![]() |
question3![]() |
answer3![]() |
---|---|---|---|---|---|---|---|
0 ![]() |
1 ![]() |
'q1' ![]() |
'str1' ![]() |
'q2' ![]() |
'str2' ![]() |
'q3' ![]() |
'str3' ![]() |
1 ![]() |
2 ![]() |
'q1' ![]() |
'str4' ![]() |
None![]() |
None![]() |
'q3' ![]() |
'str6' ![]() |
Not every project has the same number of question but questions are shared for each project.并非每个项目都有相同数量的问题,但每个项目都共享问题。 So when a specific question isn't in a project, I would like cells to be filled up with None values.
因此,当项目中没有特定问题时,我希望将单元格填充为 None 值。
I didn't found any way to do it with join or concat, but I don't know how to properly use it.我没有找到任何使用 join 或 concat 的方法,但我不知道如何正确使用它。
I would like to improve my pandas skills so my question is:我想提高我的 pandas 技能,所以我的问题是:
Is there any way to do it with pandas treatment or doing it manually by treating my DataFrames with iterrows is the only way?有什么办法可以通过 pandas 处理或通过使用 iterrows 处理我的 DataFrame 来手动完成是唯一的方法吗?
Thank you !谢谢 !
You can use cumcount
before pivoting to get your suffixes:您可以在旋转之前使用
cumcount
来获取后缀:
df['idx'] = df.groupby('projectid').cumcount() + 1
df = df.pivot(index='projectid',columns='idx')[['question','answer']]
df.columns = [''.join(map(str, col)) for col in df.columns]
print(df)
Output:: Output::
question1 question2 question3 answer1 answer2 answer3
projectid
1 'q1' 'q2' 'q3' 'str1' 'str2' 'str3'
2 'q1' 'q3' NaN 'str4' 'str6' NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.