MaxB
MaxB

Reputation: 458

Converting tuple occurences to string in dataframe column

I have a dataframe column that has the occasional tuple inserted into it. I would like to join all of these tuples into one string separated by ','.

EX

Data      People
 A        XYZ
 B        ABX,LMN
 C       ('OPP', 'GGG')
 D        OAR

I am only trying to 'target' the tuple here and convert it to a string giving the following dataframe:

Data      People
 A        XYZ
 B        ABX,LMN
 C        OPP,GGG
 D        OAR

df['People'] = df['People'].apply(','.join)

I tried this, but it ends up inserting commas in between every character in all of the 'OK' strings.

Upvotes: 2

Views: 1410

Answers (3)

Andy L.
Andy L.

Reputation: 25249

You may avoid apply by using map to create mask True on tuple. Use this mask to slice on rows having tuple and use str.join directly on it.

m = df.People.map(type).eq(tuple)
df.loc[m, 'People'] = df.loc[m, 'People'].str.join(',')


Out[2206]:
  Data   People
0    A      XYZ
1    B  ABX,LMN
2    C  OPP,GGG
3    D      OAR

Upvotes: 0

harpan
harpan

Reputation: 8631

If you must, you can do something like below.

df['People'] = df['People'].apply(lambda x: ', '.join(x) if isinstance(x,tuple) else x)

Output:

  Data  People
0   A   XYZ
1   B   ABX, LMN
2   C   OPP, GGG
3   D   QAR

Upvotes: 3

piyush daga
piyush daga

Reputation: 501

This works may not be the most elegant solution:

df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': ['AA', 'ABC, LMN', ('XYZ', 'PQR'), 'OLA']})

# Output

    A   B
0   1   AA
1   2   ABC, LMN
2   3   (XYZ, PQR)
3   4   OLA
df['B'].apply(lambda x: ','.join([val for val in x]) if isinstance(x, tuple) else x)

# Output

0          AA
1    ABC, LMN
2     XYZ,PQR
3         OLA
Name: B, dtype: object

Upvotes: 1

Related Questions