這是我寫在評論中@Boud解釋的非常粗糙的解決方案。我在這裏首先創建示例數據:
df = pd.DataFrame([
['record1', '10', 'date1', 'optional', 'comment'],
['', '', '', '', 'comment continued'],
['', '', '', '', ''],
['record2', '100', 'date2', '', 'comment'],
['', '', '', '', 'comment continued'],
['', '', '', '', 'comment continued'],
['', '', '', '', 'comment continued'],
['', '', '', '', ''],
['record3', '10000', 'date3', '', 'comment']],
columns=['col_A', 'col_B', 'col_C', 'col_D', 'col_F'])
df.replace('', np.nan, regex=True, inplace=True)
請注意,這裏的空白應該充滿NaN
,而不是空白。基本上,首先,您可以使用dropna
刪除不先使用的行。
df.dropna(axis=0, how='all', inplace=True) # drop NaN by row
然後您可以填寫col_A
以前的記錄。
new_col = []
row_name = ''
for r in df.col_A:
if not pd.isnull(r):
row_name = r
new_col.append(row_name)
df.col_A = new_col
比後,您可以將其他列由加盟字符串如下應用groupby
函數A列和彙總等列。
gr = df.groupby('col_A')
def join_str(x):
x = list(map(str, x))
x = [e for e in x if str(e) != 'nan']
return ' '.join(x)
gr.agg({'col_B' : join_str,
'col_C': join_str,
'col_D': join_str,
'col_F': join_str}).reset_index()
提示您或有抱負的答案:加載DF,由np.nan更換空白,dropna( '所有' 軸= 1),ffill(),GROUPBY(COL A到E)。適用( lambda x:'\ n'.join(x))。reset_index() – Boud
您還可以附加或提供鏈接以下載Excel表單嗎? – titipata
我已更新我的問題,嘗試減少我最初的問題的一些含糊之處。 – Tommy