Home > Software engineering >  How to only keep an item of a list within pandas dataframe
How to only keep an item of a list within pandas dataframe

Time:04-25

This is what my dataframe looks like:

df = {"a": [[1,2,3], [4,5,6]],
      "b": [[11,22,33], [44,55,66]],
      "c": [[111,222,333], [444,555,666]]}

df = pd.Dataframe(df)

I want for each cell, keep only the item that I choose its index.

I've tried doing this way to keep the first item of the list

df = df.apply(lambda x:x[0])

but it doesn't work.

Anyone can enlighten me on this ? Thanks,

CodePudding user response:

If need first value for all columns need processing lambda function elementwise by DataFrame.applymap:

df = df.applymap(lambda x:x[0])
print(df)
   a   b    c
0  1  11  111
1  4  44  444
  • Related