python - 从熊猫数据框中的系列列表中过滤行
问题描述
以上是熊猫数据框。
col1 中的值是 col2 中值的键,
例如:在第 3 行中,col1 中的“-4”对应于 col2 中的 list[12,23],类似地
在第 3 行中,col1 中的“-2”对应于 list[ 12] 在 col2 中。
我希望仅过滤掉 col1 中的 +ve 值及其在 col2 中的相应值。
我尝试了多种dict(zip(col1,col2))
过滤组合,但没有奏效..
如果有人可以帮助我,那将非常有帮助。
解决方案
这是一种使用方式pd.DataFrame.apply
和生成器理解enumerate
。
import pandas as pd
from operator import itemgetter
df = pd.DataFrame({'Member': [1, 2, 3],
'Col1': [[1, 2, 3], [-1, 2], [-4, -2, 2, 3]],
'Col2': [[[12, 23], [12], [4345]],
[[12, 23], [12]],
[[12, 23], [12], [4345], [34354]]]})
def list_filter(row):
i = ((i, j) for i, j in enumerate(row['Col1']) if j > 0)
idx, vals = zip(*i)
return list(vals), list(itemgetter(*idx)(row['Col2']))
df[['Col1', 'Col2']] = df.apply(list_filter, axis=1).values.tolist()
print(df)
Col1 Col2 Member
0 [1, 2, 3] [[12, 23], [12], [4345]] 1
1 [2] [12] 2
2 [2, 3] [[4345], [34354]] 3
推荐阅读
- django - Django 全局变量是在所有用户还是单个用户之间共享?
- powerpivot - 电源查询时间另存为日期
- wordpress - 发布新帖子后触发链接
- python - Python - 当单个 ip 元素时,将 ip 地址列表处理为字符串列表
- html - 子边框半径相同时父背景泄露
- r - R - 使用函数打印数据帧的值带来 NULL 值
- java - 如何在 Java Spring Boot 应用程序中正确地从 redis 获取数据
- r - 您可以使用 R 包 drake 制定多个计划吗?
- c - 在大型项目上运行 Clang-Tidy
- installshield - Installshield 升级带有额外组件的补丁