栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

连接pandas数据框中的所有列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

连接pandas数据框中的所有列

解决方案

sum
,但输出是
float
,因此必须转换为
int
str

df['new'] = df.sum(axis=1).astype(int).astype(str)

另一个具有

apply
function的解决方案
join
,但最慢:

df['new'] = df.apply(''.join, axis=1)

最后非常快

numpy solution
-转换为
numpyarray
再“和”:

df['new'] = df.values.sum(axis=1)

时间

df = pd.Dataframe({'A': ['1', '2', '3'], 'B': ['4', '5', '6'], 'C': ['7', '8', '9']})#[30000 rows x 3 columns]df = pd.concat([df]*10000).reset_index(drop=True)#print (df)cols = list('ABC')#not_a_robot solutionIn [259]: %timeit df['concat'] = pd.Series(df[cols].fillna('').values.tolist()).str.join('')100 loops, best of 3: 17.4 ms per loopIn [260]: %timeit df['new'] = df[cols].astype(str).apply(''.join, axis=1)1 loop, best of 3: 386 ms per loopIn [261]: %timeit df['new1'] = df[cols].values.sum(axis=1)100 loops, best of 3: 6.5 ms per loopIn [262]: %timeit df['new2'] = df[cols].astype(str).sum(axis=1).astype(int).astype(str)10 loops, best of 3: 68.6 ms per loop

编辑如果某些列的dtype不是

object
(显然是
string
s)强制转换
Dataframe.astype

df['new'] = df.astype(str).values.sum(axis=1)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/645174.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号