Home > Blockchain >  pandas appending values to a list in a column
pandas appending values to a list in a column

Time:08-26

Consider the below example, I want to append datas from column c to the list of values in column notes

df:

enter image description here

expected result:

enter image description here

CodePudding user response:

You must loop to work with lists in pandas DataFrame/Series:

for c,l in zip(df['c'], df['Notes']):
    l.append(c)

output:

    c       Notes
0   1         [1]
1   2  [12, 2, 2]
2  11    [21, 11]

used input:

df = pd.DataFrame({'c': [1,2,11],
                   'Notes': [[], [12,2], [21]]})

CodePudding user response:

You can use apply :

import pandas as pd

df = pd.DataFrame([[3, 4, 1, []], [2, 45, 2, [12, 2]], [4, 7, 11, [21]]], columns=['a', 'b', 'c', 'Notes'])

df['Notes'] = df.apply(lambda x: x['Notes']   [x['c']], axis=1)

CodePudding user response:

You can use apply function:

df.apply(lambda x: x["Notes"].append(x["c"]), axis=1)
  • Related