Reputation: 4618
Suppose I have the following dataframe:
df = pd.DataFrame({'col1': ['abc', 'defg', 'hwer', 'qwerty'], 'col2': ['123', '456', '890', '90'],
'col3': ['knlk', 'knl', 'op', 'tui']})
And I want to join the strings from each row by a specific character, I'm doing like this:
df['col4'] = df['col1'] + '_' + df['col2'] + '_' + df['col3']
But I have to keep repeating the '_'
, is there a way to do something like:
df['col4'] = '_'.join([df['col1'], df['col2'], df['col3']])
Upvotes: 3
Views: 283
Reputation: 7065
There is 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
Upvotes: 2
Reputation: 2443
df['new'] = df[['col2', 'col3']].apply(lambda x: '_'.join(x), axis=1)
Upvotes: 3
Reputation: 17322
you can use pandas.DataFrame.stack:
df['col4'] = df.stack().groupby(level=0).apply('_'.join)
df
output:
Upvotes: 3