M Arroyo
M Arroyo

Reputation: 445

Applying lambda functions to columns

I have a dataframe df

   id   values
1  34   ['de, fa qe', 'ml, fr']
2  45   ['op er, qe', 'm, qn', 'asd, qwe, zxc'] 

I want to end with:

   id   values
1  34   ['de, fa qe, ml, fr']
2  45   ['op er, qe, m, qn, asd, qwe, zxc'] 

I'm thinking about using this function

merger=lambda x, y:x+y

But I can't figure out how to apply it.

Thank you.

Upvotes: 1

Views: 115

Answers (2)

Alexander
Alexander

Reputation: 109756

Just call join using the str accessor.

df = pd.DataFrame({'id': [34, 45],
                   'values': [['de, fa qe', 'ml, fr'], 
                              ['op er, qe', 'm, qn', 'asd, qwe, zxc']]})

>>> df['values'].str.join(', ')
0                  de, fa qe, ml, fr
1    op er, qe, m, qn, asd, qwe, zxc
Name: values, dtype: object

>>> df['values'].str.join(', ').iat[-1]
'op er, qe, m, qn, asd, qwe, zxc'

Upvotes: 3

João Almeida
João Almeida

Reputation: 5097

Don't use values as a column name, it conflicts with the DataFrame attribute values.

If you have the DataFrame:

   id   column1
1  34   ['de, fa qe', 'ml, fr']
2  45   ['op er, qe', 'm, qn', 'asd, qwe, zxc']

it's just using the apply method on the Series you want. For instance:

merger=lambda x: [''.join(s) for s in x]
df.column1 = df['column1'].apply(merger)

Upvotes: 2

Related Questions