user4933255
user4933255

Reputation:

Combine each row of some Pandas columns into a list

I have a DataFrame like so.

   P1A  P1B  P1C  P1D  P1E P2A  P2B  P2C  P2D  P2E
0   4S  4S  4S  4S  4S  AC  AC  AC  AC  AC
1   9C  9C  9C  9C  9C  KS  KS  KS  KS  KS
2   JS  JS  JS  JS  JS  8S  8S  8S  8S  8S
3   TC  TC  TC  TC  TC  JS  JS  JS  JS  JS
. . .  

What I'd like is to take some column names and merge them into one column, storing their data as a list per row, like so:

             P1                   P2
0   [4S  4S  4S  4S  4S]  [AC  AC  AC  AC  AC]
1   [9C  9C  9C  9C  9C]  [KS  KS  KS  KS  KS]
2   [JS  JS  JS  JS  JS]  [8S  8S  8S  8S  8S]
3   [TC  TC  TC  TC  TC]  [JS  JS  JS  JS  JS]
. . .  

How might I accomplish this? Thank you!

Upvotes: 1

Views: 864

Answers (1)

EdChum
EdChum

Reputation: 393973

You could apply a lambda on each column group:

In [45]:
one_cols = df.columns[df.columns.str.contains('1')]
two_cols = df.columns[df.columns.str.contains('2')]
df['P1'] = df[one_cols].apply(lambda x: [' '.join(x)], axis=1)
df['P2'] = df[two_cols].apply(lambda x: [' '.join(x)], axis=1)
df

Out[45]:
  P1A P1B P1C P1D P1E P2A P2B P2C P2D P2E                P1                P2
0  4S  4S  4S  4S  4S  AC  AC  AC  AC  AC  [4S 4S 4S 4S 4S]  [AC AC AC AC AC]
1  9C  9C  9C  9C  9C  KS  KS  KS  KS  KS  [9C 9C 9C 9C 9C]  [KS KS KS KS KS]
2  JS  JS  JS  JS  JS  8S  8S  8S  8S  8S  [JS JS JS JS JS]  [8S 8S 8S 8S 8S]
3  TC  TC  TC  TC  TC  JS  JS  JS  JS  JS  [TC TC TC TC TC]  [JS JS JS JS JS]

Upvotes: 1

Related Questions