Dulat Yussupaliyev
Dulat Yussupaliyev

Reputation: 49

appending to the list in dataframe

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

Upvotes: 1

Views: 38

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195408

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])

Upvotes: 1

Alex L
Alex L

Reputation: 4241

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

Upvotes: 1

Related Questions