Home > database >  appending to the list in dataframe
appending to the list in dataframe

Time:10-31

I have dataframe in following way:

vals = [[100,200], [100,200],[100,200]]

df = pd.DataFrame({'y':vals})
df['x'] = [1,2,3]

df

how can I append y values to the lists in x column, so my final values are in the following shape?

enter image description here

thanks

CodePudding user response:

this would work

import pandas as pd

vals = [[100,200], [100,200],[100,200]]

df = pd.DataFrame({'y':vals})
df['x'] = [1,2,3]

df["last"] = [ y   [x] for x, y in zip(df["x"], df["y"]) ] 

df

enter image description here

CodePudding user response:

Try:

df["last"] = df.apply(lambda v: [*v.y, v.x], axis=1)
print(df)

Prints:

            y  x           last
0  [100, 200]  1  [100, 200, 1]
1  [100, 200]  2  [100, 200, 2]
2  [100, 200]  3  [100, 200, 3]

Or:

df["last"] = df.y   df.x.apply(lambda x: [x])
  • Related