首页 > 解决方案 > Pandas - 如何仅将列表的最后一个元素获取到另一列?

问题描述

我有一个 Pandas 数据框,其中包含一些列中的列表:

email                         A                      B
something@gmail.com    [name1, name2]    [thing1, thing2, thing3]
another@gmail.com          [name]           [thing1, thing2]

我只想在每一行中拥有每个列表的最后一个元素,如下所示:

email                    A         B
something@gmail.com    name2    thing3
another@gmail.com      name     thing2

有简单的方法吗?我最初虽然想到了类似的东西 data['newcolumn'] = data['A'][Number of row][-1],但我在做“行数”部分时有点迷失了。谢谢!

标签: pythonpandaslistdataframe

解决方案


假设您的数据框被调用df,您可以执行以下操作

def return_last_element(row):
    # If the row of the given column is list or a tuple, get the last element
    if isinstance(row, (list, tuple)):
        return row[-1]

    # Otherwise just return the value
    else:
        return row

# Loop over all columns, and apply the function to each row of each column
for col in df.columns:
    df[col] = df[col].apply(return_last_element)

推荐阅读