如何在不更改列的情况下将数据帧中所有行的值连接到单个行中? [英] How to concatenate values of all rows in a dataframe into a single row without altering the columns?
本文介绍了如何在不更改列的情况下将数据帧中所有行的值连接到单个行中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据帧输入,看起来像:
I have a data frame input that looks like:
col1 col2 col3
0 3 1 NaN
1 NaN 7 8
如何在用', '
连接行中的数据时折叠所有行?
How to collapse all rows while concatenating the data in the rows with ', '
?
所需的数据帧输出:
col1 col2 col3
0 3 1, 7 8
示例输入代码:
Sample input code:
import pandas as pd
import numpy as np
d = {'col1': ["3", np.nan], 'col2': ["1", "7"], 'col3': [np.nan, "8"]}
df = pd.DataFrame(data=d)
想到了
推荐答案
agg
+ dropna
+ str.join
.
df.agg(lambda x: ', '.join(x.dropna())).to_frame().T
col1 col2 col3
0 3 1, 7 8
还有其他解决方案,我的同龄人会为您找到它们:)
There are other solutions, my peers will find them for you :)
这篇关于如何在不更改列的情况下将数据帧中所有行的值连接到单个行中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文