python - 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]
,但我在做“行数”部分时有点迷失了。谢谢!
解决方案
假设您的数据框被调用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)
推荐阅读
- node.js - ReferenceError:未定义加载程序
- c# - 用户委托的 SAS 令牌
- typescript - TypeORM OneToMany 导致“ReferenceError:无法访问”
'在初始化之前" - java - 当 Java 应用程序被 Dockerized 时,串行端口访问失败
- windows - 操作系统如何表示 Windows 命令行?
- javascript - 如何捕获我单击的项目,以便将其传递给 API - VueJS 和 Quasar
- json - 使用 ${params} 将所有参数 jenkins 写入 JSON 文件
- python - 从两个单独的数组创建图像
- reactjs - 我不确定为什么 Office Fabric UI React 布局类不起作用
- c# - 如何将行数/列数绑定到 UniformGrid