Chris
Chris

Reputation: 3715

Convert column tuple into a string

I have a dataframe looking like this:

    ip  date    destination_bytes   source_bytes
                 count  max mean    min sum count   max mean    min sum
0   10.0.0.1    2020-11-13 13:57:00 3   3   2.0 1   6   3   5   2.666667    1   8
1   10.0.0.1    2020-11-13 13:59:00 0   0   0.0 0   0   0   0   0.000000    0   0
2   10.0.0.1    2020-11-13 14:01:00 1   2   2.0 2   2   1   1   1.000000    1   1

Which results in column names as tuples, i.e ('ip',''),('date',''),('destination_bytes','sum').

How can I convert these into joined strings, i.e ip,date,destination_bytes_sum?

Upvotes: 2

Views: 59

Answers (1)

jezrael
jezrael

Reputation: 862771

Use Index.map with strip:

df.columns = df.columns.map('_'.join).str.strip('_')

Or in list comprehension with f-strings:

df.columns = [f'{a}_{b}'.strip('_') for a, b in df.columns]

Alternative with if-else:

df.columns = [f'{a}_{b}' if b != '' else a for a, b in df.columns]

Upvotes: 3

Related Questions