Apply Lambda Function On Multiple Columns
Let's suppose that I have this DataFrame in pandas: year text_1 text_2 0 1999 ['Sunny', 'weather'] ['Foggy', 'weather'] 1 2005 ['Rainy, 'weather'
Solution 1:
Use DataFrame.applymap
if need processing each value element wise:
df[['text_1', 'text_2']] = df[['text_1', 'text_2']].applymap(' '.join)
print (df)
year text_1 text_2
01999 Sunny weather Foggy weather
12005 Rainy weather Cloudy weather
Or combine DataFrame.apply
with Series.str.join
:
df[['text_1', 'text_2']] = df[['text_1', 'text_2']].apply(lambda x: x.str.join(' '))
Solution 2:
sample data
AB0[asdf, asf][eeee, tttt]
df['combined'] = df.apply(lambda x: [' '.join(i) for i in list(x[['A','B']])], axis=1)
Output
AB combined
0[asdf, asf][eeee, tttt][asdf asf, eeee tttt]
Update
df[['A','B']] = df.apply(lambda x: pd.Series([' '.join(x['A']),' '.join(x['B'])]), axis=1)
Output
AB0 asdf asf eeee tttt
Post a Comment for "Apply Lambda Function On Multiple Columns"