【问题标题】:Python - Pandas How to get all possible combinations from a group by in a dataframePython - Pandas 如何从数据框中的组中获取所有可能的组合
【发布时间】:2020-06-22 14:06:05
【问题描述】:

我有一个包含 4 列的数据框。前 3 个列仅对我有用。我想获取 1 个员工编号/客户编号/日期的所有可能的事件编号组合。例如,在下面的照片中:

https://i.stack.imgur.com/5r3vQ.png

这是我想要得到的输出:

https://i.stack.imgur.com/JiroJ.png

请注意,对我来说顺序并不重要,这意味着组合 123,4567 与组合 4567,123 相同。因此,如果有 5 例 123,4567 和 8 例 4567,123,我只想要 123,4567 和 13 的一行。

有什么想法吗?我还是 Python 新手,有点卡住了!

非常感谢:)

编辑:

这段代码似乎可以工作:


import pandas as pd
import time
from collections import Counter
from itertools import chain, combinations

import sys
sys.path.append('C:/Config Python')
import config
import pyodbc  
import pandas as pd
import numpy as np

pd.options.display.max_colwidth = 150
  
#Build teradata connection function  
def td_connect(usr, pwd, DRIVER = 'XXX', DBCNAME = 'YYY'):  
    try:  
        conn_td = pyodbc.connect(DRIVER=DRIVER, DBCNAME=DBCNAME, UID=usr, PWD=pwd, autocommit = True)  
        return conn_td  
    except IOError as e:  
        print('I/O error !')   
        

          
#Give the query you wish to run           
sql = """ 

The code is here

"""  
  
#Put td login information  
conn = td_connect(usr=config.username,pwd=config.password)  
  
#get data  
df = pd.read_sql(sql, conn)  

df

gp = df.groupby(['Employee no', 'Client number', 'Date'])

d = dict()
for name, group in gp:
    l = group['Event Number'].to_list()    
    try:
        d[len(l)].append(l)
    except KeyError:
        d[len(l)] = [l]
d

meets = []
for i in d.keys():
    meets.append(Counter(chain.from_iterable(combinations(line, i) for line in d[i])))
    
print(meets)

【问题讨论】:

  • 请考虑分享你到目前为止所做的事情。

标签: python pandas pandas-groupby itertools


【解决方案1】:

灵感来自Concatenate strings from several rows using Pandas groupby

df['Combinations'] = df.groupby(['Employee no', 'Client number', 'Date'])['Event Number'].transform(lambda x: ",".join(x))
df['Counts'] = df.groupby(['Employee no', 'Client number', 'Date']).counts()['Event number'] 
result = df[['Employee no', 'Client number', 'Date', 'Combinations', 'Counts']].drop_duplicates()

【讨论】:

  • 非常感谢!我在第一线。它似乎不适用于浮点数。它在所有数字之间放置一个 ,
  • 确认您使用pandas.read_csv,添加参数seperator=","。不过,请提供您正在使用的代码,正如@Alper 之前在评论中询问的那样。您可以编辑以前的帖子。
猜你喜欢
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
相关资源
最近更新 更多