Home > Enterprise >  Pandas: Modify list elements of a column based on another column
Pandas: Modify list elements of a column based on another column

Time:06-24

I need to modify element of list in a column with another column value.

df is as:

Letter      Action
'2G'       ['a','b']
'2G'       ['a','c','d']
'3G'       ['a']
'5G'       ['a','b','c','d','e']
'4G'       ['d']

I expect

Action
['2Ga','2Gb']
['2Ga','2Gc','2Gd']
['3Ga']
['5Ga','5Gb','5Gc','5Gd','5Ge']
['5Gd']

my own attempt which is slow and returns a map object.

df['new'] = df.Action.apply(lambda x : map(lambda z: df['Letter'] z ,x)) 

CodePudding user response:

try explode and .agg(list) after applying a sum row wise.

if you happen to have string object of a list you can apply pd.eval to the column

df['Action'].map(pd.eval)

df1 = df.explode('Action').sum(axis=1).groupby(level=0).agg(list)

df1 = df.explode('Action')[['Letter','Action']]\
        .sum(axis=1).groupby(level=0).agg(list)


0                   [2Ga, 2Gb]
1              [2Ga, 2Gc, 2Gd]
2                        [3Ga]
3    [5Ga, 5Gb, 5Gc, 5Gd, 5Ge]
4                        [4Gd]
dtype: object

CodePudding user response:

This should do it:

import pandas as pd
import json

def join_columns(s):
    letter = s.loc['Letter']
    action = s.loc['Action']
    joined_columns = [letter   value for value in action]

    return joined_columns


df['new_Action'] = df.apply(join_columns, axis=1)

The output:

|   | Letter | Action          | new_Action                 |
|---|--------|-----------------|----------------------------|
| 0 | 2G     | [a, b]          | [2Ga, 2Gb]                 |
| 1 | 2G     | [a, c, d]       | [2Ga, 2Gc, 2Gd]            |
| 2 | 3G     | [a]             | [3Ga]                      |
| 3 | 5G     | [a, b, c, d, e] | [5Ga, 5Gb, 5Gc, 5Gd, 5Ge]  |
| 4 | 4G     | [d]             | [4Gd]                      |
  • Related