首页 > 解决方案 > Selecting the last element of a list inside a pandas dataframe

问题描述

I have a pandas dataframe with a column containing of list values with example data as:

datetime.              column1
2021-04-10 00:03 00.   [20.0, 21.6, 30.7]
2021-04-10 00:06 00.   [10.0, 20.6, 20.7]
2021-04-10 00:09 00.   [20.0, 21.5, 10.7]

I would like to select the last element of the column1 with the expected output as

datetime.              column1
2021-04-10 00:03 00.   30.7
2021-04-10 00:06 00.   20.7
2021-04-10 00:09 00.   10.7

标签: pythonpandasnumpydata-science

解决方案


df.column1 = df.column1.apply(lambda x: x[-1])    
print(df)

Prints:

              datetime.  column1
0  2021-04-10 00:03 00.     30.7
1  2021-04-10 00:06 00.     20.7
2  2021-04-10 00:09 00.     10.7

推荐阅读