这是我写在评论中@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