1

I have a pandas dataframe where one column consists of lists:

import pandas as pd
df = pd.DataFrame({"a" : [[1,2,3], [4,5,6], [7,8,9]]})

I want to add, e.g., the first and last index of each list. For that I use apply:

df['a'].apply(lambda x: x[0] + x[-1])

This acts on each row individually, which can be quite intensive if the dataframe is large. Is there a way to vectorize this operation?

N08
  • 1,205
  • 9
  • 19

1 Answers1

1

Use DataFrame.iloc:

df.iloc[0]+df.iloc[-1]
a     4
b    10
c    16
dtype: int64
ansev
  • 28,746
  • 5
  • 11
  • 29
  • Thanks. I was very unclear in my OP, I apologize for that - I need `axis=1` (please see updated post) – N08 Nov 18 '19 at 10:26