pandas数据帧中值之间的相交

时间:2017-01-23 22:26:04

标签: python pandas

问题陈述:

创建新的pandas dataframe列,显示两个不同列中行值的1(交叉)或0(无交点)的布尔值:row_modscol_mods。添加另一列以显示那些重叠是什么。如下例所示,intersect采用布尔值,common显示交叉值。

渲染的pandas数据帧就是我所拥有的,绘制的部分是我正在寻找的:

enter image description here

设定:

# data
n = np.nan
congruent = pd.DataFrame.from_dict(  
         {'row': ['x','a','b','c','d','e','y'],
            'x': [ n,  5,   5,  5,  5,  5, 5],
            'a': [ 5, n, -.8,-.6,-.3, .8, .01],
            'b': [ 5,-.8,  n, .5, .7,-.9, .01],
            'c': [ 5,-.6, .5,  n, .3, .1, .01],
            'd': [ 5,-.3, .7, .3,  n, .2, .01],
            'e': [ 5, .8,-.9, .1, .2,  n, .01],
            'y': [ 5, .01, .01, .01, .01,  .01, n],
       }).set_index('row')
congruent.columns.names = ['col']
memberships = {'a':['vowel'], 'b':['consonant'], 'c':['consonant'], 'd':['consonant'], 'e':['vowel'], 'y':['consonant', 'vowel'], '*':['wildcard']}

# format stacked df
cs = congruent.stack().to_frame()
cs.columns = ['score']
cs.reset_index(inplace=True)
cs.columns = ['row', 'col', 'score']

# filter col entries not found in membership dict keys
cs['elim'] = (cs['row'].isin(memberships.keys())) & (cs['col'].isin(memberships.keys()))
cs_2 = cs[cs['elim'] == True]

# map col entires to membership dict values
cs_2['row_mods'] = cs_2['row'].map(memberships)
cs_2['col_mods'] = cs_2['col'].map(memberships)

如何在两个不同列的行中跨越两个值执行交集?

2 个答案:

答案 0 :(得分:1)

由于您对PANDAS操作显然感到满意,我只提供Python交叉逻辑:

common = list(set(row_mods).intersection(set(col_mods)))
intersect = len(common) > 0

简而言之,您将每个mod列表转换为一个集合,然后使用Python内置的交集方法。将结果转回列表。

这能解决您的问题吗?

答案 1 :(得分:1)

尝试这个伴侣:

步骤1,定义功能:

def check_row (row_mods, col_mods):

    common = []

    intersect = 0

    for x in col_mods:

        if x in row_mods:

            intersect = 1
            common.append(x)

    if (intersect == 0):

        common.append(np.nan)

    return (intersect, common)

步骤2,应用功能:

cs_2['intersect'] = ''
cs_2['common'] = ''

for index in cs_2.index:

    (intersect, common) = check_row(cs_2.loc[index,'row_mods'], cs_2.loc[index,'col_mods'])

    cs_2.loc[index,'intersect'] = intersect
    cs_2.loc[index,'common'] = [x for x in common]
希望它有所帮助!如果它支持/检查答案:)