Поскольку дублируются Date
значения, создается помощник Series
с тестовыми не пропущенными значениями с кумулятивной суммой на Series.cumsum
и переход к GroupBy.agg
с агрегатом GroupBy.first
и join
:
g = df['Date'].notna().cumsum()
df = df.groupby(g).agg({'Date':'first', 'Comment': ' '.join}).reset_index(drop=True)
print (df)
Date Comment
0 03/07/20 Comment 1
1 03/07/20 Comment b 1 Comment b 2 Comment b 3
2 04/07/20 Comment c 1 Comment c 1
Для общего решения для агрегирования сначала для всех столбцов без Comment
возможно создание динамического словаря c:
print (df.columns)
Index(['Date', 'Comment', 'post_id'], dtype='object')
g = df['Date'].notna().cumsum()
d = dict.fromkeys(df.columns.difference(['Comment']), 'first')
d['Comment'] = ' '.join
print (d)
{'Date': 'first', 'post_id': 'first',
'Comment': <built-in method join of str object at 0x00000000028761B0>}
df = df.groupby(g).agg(d).reset_index(drop=True)
print (df)
Date post_id Comment
0 03/07/20 1.0 Comment 1
1 03/07/20 2.0 Comment b 1 Comment b 2 Comment b 3
2 04/07/20 3.0 Comment c 1 Comment c 1
Аналогичная идея с перезаписью Comment
ключа в словаре для того же порядка столбцов в выходном DataFrame:
print (df.columns)
Index(['Date', 'Comment', 'post_id'], dtype='object')
g = df['Date'].notna().cumsum()
d = dict.fromkeys(df.columns, 'first')
d['Comment'] = ' '.join
print (d)
{'Date': 'first',
'Comment': <built-in method join of str object at 0x00000000028761B0>,
'post_id': 'first'}
df = df.groupby(g).agg(d).reset_index(drop=True)
print (df)
Date Comment post_id
0 03/07/20 Comment 1 1.0
1 03/07/20 Comment b 1 Comment b 2 Comment b 3 2.0
2 04/07/20 Comment c 1 Comment c 1 3.0