如何在 pandas 中合并行 [英] How to combine rows in pandas

查看:86
本文介绍了如何在 pandas 中合并行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据集

I have a dataset like this

df = pd.DataFrame({'a' : ['a', 'b' , 'b', 'a'], 'b': ['a', 'b' , 'b', 'a'] })

我想合并前两行并获得像这样的数据集

And i want to combine first two rows and get dataset like this

df = pd.DataFrame({'a' : ['a b' , 'b', 'a'], 'b': ['a b' , 'b', 'a'] })

没有规则,只有前两行.我不知道如何合并行,所以我按以下方法通过transpose()来合并创建"方法

no rules but first two rows. I do not know how to combine row so i 'create' method to combine by transpose() as below

db = df.transpose()
db["new"] = db[0].map(str) +' '+ db[1]
db.drop([0, 1], axis=1, inplace=True) # remove these two columns
cols = db.columns.tolist() # re order 
cols = cols[-1:] + cols[:-1]
db = db[cols]
df = db.transpose() # reverse operation
df.reset_index()

它有效,但我认为有一种更简单的方法

It works but i think there is an easier way

推荐答案

您可以简单地添加两行

df.loc[0] = df.loc[0]+ df.loc[1]
df.drop(1, inplace = True)

你得到

    a   b
0   ab  ab
2   b   b
3   a   a

看起来更漂亮:)

df.loc[0]= df[:2].apply(lambda x: ''.join(x))
df.drop(1, inplace = True)

这篇关于如何在 pandas 中合并行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆