[英]How to combine multiple rows into single row by adding columns with pandas?
[英]How to combine two rows in single row in pandas
不幸的是,您將不得不遍歷行和列到 select 出非空單元格。 這是您的表格的簡化版本。
import pandas as pd
df =pd.DataFrame({
'em':['em1','em2','em3','em1','em2','em3'],
'a':['a1','a2','a3','','',' '],
'b':['','','','b1','b2','b3']
})
print(df)
df2 =pd.DataFrame()
for em in set(df['em']):
df_em = df[df['em']==em]
df2 = df2.append(df_em.iloc[[0]], ignore_index = True)
for c in range(len(df.columns)):
if df_em.iat[0,c].strip() == '':
df2.iat[len(df2)-1,c] = df_em.iat[1,c]
else:
df2.iat[len(df2)-1,c] = df_em.iat[0,c]
print('\n\n',df2)
Output:
em a b
0 em1 a1
1 em2 a2
2 em3 a3
3 em1 b1
4 em2 b2
5 em3 b3
em a b
0 em1 a1 b1
1 em2 a2 b2
2 em3 a3 b3
如果您的Name
和Email
和Subject
列對於匹配的行是相等的,並且您知道要“合並”的行組的索引,您可以嘗試以下步驟:
combine_first
填充來自不同行組的 null 值。在您的情況下,行組是前三個和后三個。
new_df = df.set_index(["Name", "Email", "Subject"])
# Combine first 3 rows with last 3
combined = new_df.iloc[:3].combine_first(new_df.iloc[3:])
結果:
Q.1 Q.2 Q.3 Q.4 Q.5 Q.6 Q.7 Q.8
Name Email Subject
MOHD AQUIL aquilchoudhary@gmail.com History B C B A B A B D
Shweta Rangarishweta@gmail.co History B A B D B C B A
Suraj surajdas112@gmail.com History B A B B B A B B
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.