![](/img/trans.png)
[英]Python / Pandas - Merge columns with the same index in a single cell
[英]Merge columns with same index into 1 single column (pandas)
我有一個dataframe我要改造。 我想將列合並在一起,並將具有相同 ID 的值顯示為單獨的行。
所以從這個:
id children1 children2 children3
1 No Children NaN NaN
2 12-16 years 17+ years Nan
3 No Children Nan Nan
4 5-7 years 8-11 years 12-16 years
為此:
id children
1 No Children
2 12-16 years
2 17+ years
3 No Children
4 5-7 years
4 8-11 years
4 12-16 years
是否有捷徑可尋?
數據:
{'id': [1, 2, 3, 4],
'children1': ['No Children', '12-16 years', 'No Children', '5-7 years'],
'children2': [nan, '17+ years', nan, '8-11 years'],
'children3': [nan, nan, nan, '12-16 years']}
我認為您正在尋找將列轉換為索引的stack
方法。 現在要獲得確切的形狀,您需要set_index
使用“id”設置索引(以便在stack
ing 時將“id”保留為索引)。
out = df.set_index('id').stack().droplevel(1).rename('children').reset_index()
Output:
id children
0 1 No Children
1 2 12-16 years
2 2 17+ years
3 3 No Children
4 4 5-7 years
5 4 8-11 years
6 4 12-16 years
new = (df.set_index('id').agg(list,1)#Put all row values into a list except id
.explode()#Ensure each element in a list is put in a row
.replace('Nan', np.nan)# Make Nan -> NaN
.dropna()#Drop all NaNs
.to_frame('Children')#Rename column 0 to Childresn
)
結果
Children
id
1 NoChildren
2 12-16years
2 17+years
3 NoChildren
4 5-7years
4 8-11years
4 12-16years
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.