1

I am working with a pandas dataframe and trying to concatenate multiple string and numbers into one string.

This works

df1 = pd.DataFrame({'Col1': ['a', 'b', 'c'], 'Col2': ['a', 'b', 'c']})
df1.apply(lambda x: ', '.join(x), axis=1)

0    a, a
1    b, b
2    c, c

How can I make this work just like df1?

df2 = pd.DataFrame({'Col1': ['a', 'b', 1], 'Col2': ['a', 'b', 1]})
df2.apply(lambda x: ', '.join(x), axis=1)

TypeError: ('sequence item 0: expected str instance, int found', 'occurred at index 2')
1
  • 2
    try changing lambda x: ', '.join(x) to lambda x: ', '.join(str(x)) Commented May 24, 2017 at 20:18

3 Answers 3

5

Consider the dataframe df

np.random.seed([3,1415])
df = pd.DataFrame(
    np.random.randint(10, size=(3, 3)),
    columns=list('abc')
)

print(df)

   a  b  c
0  0  2  7
1  3  8  7
2  0  6  8

You can use astype(str) ahead of the lambda

df.astype(str).apply(', '.join, 1)

0    0, 2, 7
1    3, 8, 7
2    0, 6, 8
dtype: object

Using a comprehension

pd.Series([', '.join(l) for l in df.values.astype(str).tolist()], df.index)

0    0, 2, 7
1    3, 8, 7
2    0, 6, 8
dtype: object
Sign up to request clarification or add additional context in comments.

1 Comment

This is great! Thank you
2
In [75]: df2
Out[75]:
  Col1 Col2 Col3
0    a    a    x
1    b    b    y
2    1    1    2

In [76]: df2.astype(str).add(', ').sum(1).str[:-2]
Out[76]:
0    a, a, x
1    b, b, y
2    1, 1, 2
dtype: object

Comments

1

You have to convert column types to strings.

import pandas as pd
df2 = pd.DataFrame({'Col1': ['a', 'b', 1], 'Col2': ['a', 'b', 1]})
df2.apply(lambda x: ', '.join(x.astype('str')), axis=1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.