Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中反转组/项_Python_Python 3.x - Fatal编程技术网

在Python中反转组/项

在Python中反转组/项,python,python-3.x,Python,Python 3.x,我有一张这样的桌子: import pandas as pd import numpy as np # Create initial dataframe data = {'Group': ['A', 'B'], 'Item': [['a','b','c'], ['b','c','d']]} df = pd.DataFrame(data=data) Group Item 0 A [a, b, c] 1 B [b, c, d] table = {'A': ['a',

我有一张这样的桌子:

import pandas as pd
import numpy as np

# Create initial dataframe
data = {'Group': ['A', 'B'], 'Item': [['a','b','c'], ['b','c','d']]}
df = pd.DataFrame(data=data)

    Group   Item
0   A   [a, b, c]
1   B   [b, c, d]
table = {'A': ['a', 'b', 'c'], 'B': ['b', 'c', 'd']}

revtable = dict()
for v,keys in table.items():
    for k in keys:
        revtable.setdefault(k,[]).append(v)

print(revtable)
# {'a': ['A'], 'b': ['A', 'B'], 'c': ['A', 'B'], 'd': ['B']}
组 项目 A. a、 b,c B b、 c,d
假设您的表是熊猫数据框的形式,您可以尝试以下方法:

import pandas as pd
import numpy as np

# Create initial dataframe
data = {'Group': ['A', 'B'], 'Item': [['a','b','c'], ['b','c','d']]}
df = pd.DataFrame(data=data)

    Group   Item
0   A   [a, b, c]
1   B   [b, c, d]
table = {'A': ['a', 'b', 'c'], 'B': ['b', 'c', 'd']}

revtable = dict()
for v,keys in table.items():
    for k in keys:
        revtable.setdefault(k,[]).append(v)

print(revtable)
# {'a': ['A'], 'b': ['A', 'B'], 'c': ['A', 'B'], 'd': ['B']}
*上面的代码片段取自,其中包括对代码的更详细解释

# Perform groupby operation 
df = df.groupby('Item')['Group'].apply(list).reset_index(name='Group')

    Item    Group
0   a     [A]
1   b     [A, B]
2   c     [A, B]
3   d     [B]

如果您在pandas中工作,您可以使用“explode”来解包项目,也可以在分组阶段使用“to_list”lambda

这里有一些关于“爆炸”方法的信息

爆炸

分解然后使用“to_list”lambda


不是最有效的,但非常简短:

>>> table = {'A': ['a', 'b', 'c'], 'B': ['b', 'c', 'd']}
>>> reversed_table = {v: [k for k, vs in table.items() if v in vs] for v in set(v for vs in table.values() for v in vs)}
>>> print(reversed_table)
{'b': ['A', 'B'], 'c': ['A', 'B'], 'd': ['B'], 'a': ['A']}

对于字典,您通常会这样处理:

import pandas as pd
import numpy as np

# Create initial dataframe
data = {'Group': ['A', 'B'], 'Item': [['a','b','c'], ['b','c','d']]}
df = pd.DataFrame(data=data)

    Group   Item
0   A   [a, b, c]
1   B   [b, c, d]
table = {'A': ['a', 'b', 'c'], 'B': ['b', 'c', 'd']}

revtable = dict()
for v,keys in table.items():
    for k in keys:
        revtable.setdefault(k,[]).append(v)

print(revtable)
# {'a': ['A'], 'b': ['A', 'B'], 'c': ['A', 'B'], 'd': ['B']}

您想分享您尝试过的内容吗?您在哪里遇到困难?您的表是如何存储的?显示一些示例代码!正如其他人所说,发布一些代码。你试过什么?这是熊猫数据帧吗?