假设我具有以下数据框:
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']])
答案 0 :(得分:2)
答案 1 :(得分:2)
df['new'] = df[['col2', 'col3']].apply(lambda x: '_'.join(x), axis=1)
答案 2 :(得分:1)
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