Pandas数据帧中的分组匹配

2024-10-06 10:32:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据帧,它有两列。第一列表示项的name,第二列表示它的一些属性,这些属性被编码为整数。一个项目可以有多个属性。这是一个样本

    name                ids
0   A                   147 616 813
1   B                   51 616 13 813
2   C                   776
3   D                   51 671 13 813 1092
4   E                   13 404 492 903 1093

有300个这样的独特属性被编码为整数,然后在id列的字符串中表示。我想要达到的目标:

  1. 对于每个id,找到它出现的行。例如,为了检查id13,我将获取1, 3 and 4行。你知道吗
  2. 在我们的数据集中,与这个id一起出现的唯一id是什么?例如,对于id13: [51, 616, 813, 671, 1092, 404, 492, 903, 1093]
  3. 一旦我们有了每个id的分组行,如何比较给定id是否在该组中?例如,我想检查id52是否与id13一起出现过,如果是,在哪里出现过,出现了多少次?你知道吗

我想了这么久,但没有一个有效的方法来获得前两个和一个有效的方法以及DS的3)。请帮帮我!你知道吗


Tags: and数据项目方法字符串nameidids
2条回答

以下是三项职能的建议:

import pandas as pd
# first we create the data
data = pd.DataFrame({'name': ['A','B','C','D','E'],
                'ids': ['147 616 813','51 616 13 813','776','51 671 13 813 
1092','13 404 492 903 1093']})

def func1(num, series):
    # num must be an int
    # series a Pandas series
    tx = series.apply(lambda x: True if str(num) in x.split() else False)

    output_list = series.index[tx].tolist()

    return output_list

 def func2(num, series):
    # num must be an int
    # series a Pandas series
    series = series.iloc[func1(num, series)]

    series = series.apply(lambda x: x.split()).tolist()

    output_list = set([item for sublist in series for item in sublist])
    output_list.remove(str(num))
    return list(output_list)

def func3(num1,num2,series):
    # num1 must be an int
    # num2 must be an int
    # series a Pandas series

    if str(num1) in func2(num2, series):
        num1_index = func1(num1, series)
        num2_index = func1(num2, series)
        return list(set(num1_index) & set(num2_index))
    else:
        return 'no match'

然后你可以测试他们:

func1(13, data['ids'])
func2(13, data['ids'])
func3(13,51,data['ids'])

不使用任何for循环的解决方案

import pandas as pd
import numpu as np

df = pd.DataFrame({'name':'A B C D E'
                   .split(),'ids':['147 616 813','51 616 13 813','776','51 671 13 813 1092','13 404 492 903 1093']})

#Every input of i_d to functions in int
#to get indexes where id occurs
def rows(i_d):
    i_d = str(i_d)
    pattern1 = "[^0-9]" +i_d+"[^0-9]"
    pattern2 = i_d+"[^0-9]"    
    pattern3 = "[^0-9]" +i_d 

    mask = df.ids.apply(lambda x: True if (len(re.findall(pattern1,x)) > 0) | (len(re.findall(pattern2,x))) | (len(re.findall(pattern3,x)) > 0) else False)

    return df[mask].index.tolist()

#to get other ids occuring with the id in discussion
def colleagues(i_d):
    i_d = str(i_d)

    df.loc[rows(i_d),'temp'] = 1
    k =list(set(df.groupby('temp').ids.apply(lambda x: ' '.join(x)).iloc[0].split()))
    k.remove(i_d)
    df.drop('temp',axis=1,inplace=True)

    return k

#to get row indexes where 2 ids occur together
def third(i_d1,i_d2):
    i_d1 = str(i_d1)
    i_d2 = str(i_d2)

    common_rows = list(np.intersect1d(rows(i_d1),rows(i_d2)))
    if len(common_rows) > 0:
        return print('Occured together at rows ',common_rows)
    else:
        return print("Didn't occur together")

相关问题 更多 >