If I have a dataframe with elements of list type in it. Now I want to use pandas or numpy to replace each element(each list) of this dataframe to second element of this element(list). How can I do that? I wrote the below code to make a trial dataframe.
import pandas as pd
df = pd.DataFrame({'a':[[1,7],[0,5]],'b':[[3,1],[4,0]],'c':[[1,4],[2,0]]})
My df looks like:
a b c
0 [1,7] [3,1] [1,4]
1 [0,5] [4,0] [2,0]
Now I want df to be changed like shown below:
a b c
0 7 1 4
1 5 0 0
I tried using replace function, lambda function etc but nothing worked.
I don't want to use loops or anything that takes time to run.
CodePudding user response:
here is one way to do it, using applymap
df.applymap(lambda x: x[1])
a b c
0 7 1 4
1 5 0 0