python - Pandas:如何检查列表类型的列是否在数据框中

标签 python pandas

如何从列表列创建新的列表列

我的数据框:

id    x    list_id
1     20   [2, 4]
2     10   [1, 3]
3     10   [1]
4     30   [1, 2]

我想要的:

id    x    list_id    list_x
1     20   [2, 4]     [10, 30]
2     10   [1, 3]     [20, 10]
3     10   [1]        [20]
4     30   [1, 2]     [20, 10]

我的第一个想法是遍历每一行,然后检查 id 是否在列表中

for index, row in df.iterrows():
  if ( df['id'].isin(row['list_id']) ):
     do_somthing

但它不起作用,任何建议!!

最佳答案

使用列表理解:

df.loc[:,'list_x'] = [df.x[df['id'].isin(l)].values for l in df.list_id]

带有虚拟数据的完整示例:

import pandas as pd

data= {
    'id': [1,2,3,4],
    'x': [20,10,10,30],
    'list_id': [[2,4],[1,3],[1],[1,2]],
}

df = pd.DataFrame(data)

df.loc[:,'list_x'] = [df.x[df['id'].isin(l)].values for l in df.list_id]

输出

print df

  list_id   x    list_x
1  [2, 4]  20  [10, 30]
2  [1, 3]  10  [20, 10]
3     [1]  10      [20]
4  [1, 2]  30  [20, 10]

关于python - Pandas:如何检查列表类型的列是否在数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44982071/

相关文章:

python - 为什么每个级别都需要 __init__.py?

python - 高效的 Python 搜索算法,用于在移动时间间隔内查找匹配项

python - 如何更改 python 数据框中的标题行

python - Pandas:如何剪辑数据帧并获取替换值的数量

Python:将列中的 JSON 结构扩展为同一数据帧中的列

python - 如何更改python数据框的内容?

python - Microsoft Visual Studio 2013 中没有名为 Flask 的模块

python - 如何将 Pandas 数据框字符串值转换为数值

python - Python 的 "with"是一元的吗?

python - Pandas 根据当前 df 中的列创建一个新的 df