Home > Blockchain >  How to update a pandas column
How to update a pandas column

Time:08-03

Given the following dataframe

col1   col2
1      ('A->B', 'B->C')
2      ('A->D', 'D->C', 'C->F')
3      ('A->K', 'K->M', 'M->P')
... 

I want to convert this to the following format

 col1   col2
 1      'A-B-C'
 2      'A-D-C-F'
 3      'A-K-M-P'
 ... 

Each sequence shows an arc within a path. Hence, the sequence is like (a,b), (b,c), (c,d) ...

CodePudding user response:

Given

df = pd.DataFrame({
    'col1': [1, 2, 3],
    'col2': [
        ('A->B', 'B->C'),
        ('A->D', 'D->C', 'C->F'),
        ('A->K', 'K->M', 'M->P'),
    ],
})

You can do:

df['col2'] = df['col2'].apply(
    lambda t: '-'.join([x.partition('->')[0] for x in t])
)

Although I may recommend splitting this complex lambda expression into its own function.

CodePudding user response:

def merge_values(val):
    val = [x.split('->') for x in val]
    out = []
    for char in val:
        out.append(char[0])
    out.append(val[-1][1])
    return '-'.join(out)

df['col2'] = df['col2'].apply(merge_values)
print(df)

Output:

   col1     col2
0     1    A-B-C
1     2  A-D-C-F
2     3  A-K-M-P
  • Related