繁体   English   中英

加入pandas系列琴弦

[英]Join pandas series of strings

假设我有以下数据框:

df = pd.DataFrame({'col1': ['abc', 'defg', 'hwer', 'qwerty'], 'col2': ['123', '456', '890', '90'],
                  'col3': ['knlk', 'knl', 'op', 'tui']})

我想通过特定字符连接每一行的字符串,我这样做:

df['col4'] = df['col1'] + '_' + df['col2'] + '_' + df['col3']

但我必须不断重复'_' ,有没有办法做这样的事情:

df['col4'] = '_'.join([df['col1'], df['col2'], df['col3']])

你可以使用pandas.DataFrame.stack

df['col4'] = df.stack().groupby(level=0).apply('_'.join)
df

输出:

在此处输入图片说明

df['new'] = df[['col2', 'col3']].apply(lambda x: '_'.join(x), axis=1)

Series.str.cat

df["col4"] = df[df.columns[0]].str.cat(df[df.columns[1:]], sep="_")
df
#      col1 col2  col3           col4
# 0     abc  123  knlk   abc_123_knlk
# 1    defg  456   knl   defg_456_knl
# 2    hwer  890    op    hwer_890_op
# 3  qwerty   90   tui  qwerty_90_tui

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM