通过迭代在Pandas DataFrame中合并行 [英] Combining rows in pandas DataFrame by iterating
本文介绍了通过迭代在Pandas DataFrame中合并行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从以下DataFrame中获得预期的结果
How can I achieve the expected result from the following DataFrame
df
col_1 col_2 col_3
0 Non-Saved www.google.com 20,567
1 www.facebook.com
2 www.linkedin.com
3 Saved www.Quora.com 6,337
4 www.gmail.com
预期结果:
col_1 col_2 col_3
0 Non-Saved www.google.com 20,567
www.facebook.com
www.linkedin.com
1 Saved www.Quora.com 6,337
www.gmail.com
通过合并col_1和col_3中的空字符串,从5行到2行.另外,将col_2中的值串联到一个单元格中.谁能帮助我使用用户定义的功能来做到这一点?
From 5 rows to 2 rows by merging the empty strings in col_1 and col_3. Also, concatenating values in col_2 into one cell. Can anyone help me with an user-defined function to do this?
推荐答案
让我们尝试:
df = df.apply(lambda x: x.str.strip()).replace('',np.nan)
df.groupby(df.col_1.ffill())\
.agg({'col_2': lambda x: ' '.join(x) ,'col_3':'first'})\
.reset_index()
输出:
col_1 col_2 col_3
0 Non-Saved www.google.com www.facebook.com www.linkedin.com 20,567
1 Saved www.Quora.com www.gmail.com 6,337
这篇关于通过迭代在Pandas DataFrame中合并行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文