python - 将 Pandas 系列向量化查找到字典

标签 python pandas numpy

问题陈述:

一个 pandas dataframe 列系列,same_group 需要根据两个现有列 rowcol 的值从 bool 值创建。如果一行中的两个单元格在字典 memberships 中具有相似值(相交值),则该行需要显示 True,否则为 False(没有相交值)。我如何以矢量化方式执行此操作(不使用应用)?

设置:

import pandas as pd
import numpy as np 
n = np.nan
memberships = {
    'a':['vowel'],
    'b':['consonant'],
    'c':['consonant'],
    'd':['consonant'],
    'e':['vowel'],
    'y':['consonant', 'vowel']
}

congruent = pd.DataFrame.from_dict(  
         {'row': ['a','b','c','d','e','y'],
            'a': [ n, -.8,-.6,-.3, .8, .01],
            'b': [-.8,  n, .5, .7,-.9, .01],
            'c': [-.6, .5,  n, .3, .1, .01],
            'd': [-.3, .7, .3,  n, .2, .01],
            'e': [ .8,-.9, .1, .2,  n, .01],
            'y': [ .01, .01, .01, .01,  .01, n],
       }).set_index('row')
congruent.columns.names = ['col']

snippet of dataframe cs

cs = congruent.stack().to_frame()
cs.columns = ['score']
cs.reset_index(inplace=True)
cs.head(6)

snippet of dataframe cs stacked

期望的目标:

finest drawing of added pandas column

我如何根据对字典的查找来创建这个新列?

请注意,我试图找到交集,而不是等价。例如,第 4 行的 same_group 应该为 1,因为 ay 都是元音(尽管 y 是“有时是元音”,因此属于辅音和元音组)。

最佳答案

# create a series to make it convenient to map
# make each member a set so I can intersect later
lkp = pd.Series(memberships).apply(set)

# get number of rows and columns
# map the sets to column and row indices
n, m = congruent.shape
c = congruent.columns.to_series().map(lkp).values
r = congruent.index.to_series().map(lkp).values

print(c)
[{'vowel'} {'consonant'} {'consonant'} {'consonant'} {'vowel'}
 {'consonant', 'vowel'}]

print(r)
[{'vowel'} {'consonant'} {'consonant'} {'consonant'} {'vowel'}
 {'consonant', 'vowel'}]

# use np.repeat, np.tile, zip to create cartesian product
# this should match index after stacking
# apply set intersection for each pair
# empty sets are False, otherwise True
same = [
    bool(set.intersection(*tup))
    for tup in zip(np.repeat(r, m), np.tile(c, n))
]

# use dropna=False to ensure we maintain the
# cartesian product I was expecting
# then slice with boolean list I created
# and dropna
congruent.stack(dropna=False)[same].dropna()

row  col
a    e      0.80
     y      0.01
b    c      0.50
     d      0.70
     y      0.01
c    b      0.50
     d      0.30
     y      0.01
d    b      0.70
     c      0.30
     y      0.01
e    a      0.80
     y      0.01
y    a      0.01
     b      0.01
     c      0.01
     d      0.01
     e      0.01
dtype: float64

产生想要的结果

congruent.stack(dropna=False).reset_index(name='Score') \
    .assign(same_group=np.array(same).astype(int)).dropna()

enter image description here

关于python - 将 Pandas 系列向量化查找到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41621279/

相关文章:

python - 查找 pandas 数据帧的列和行中所有重复模式的所有索引/实例

python - 用元组列表填充数据框列

python - 递归乘法的有效方法

python - 生成随机数以获得固定和(python)

python - 无法通过 Gino (异步 sqlalchemy 包装器)连接到 SQLite 数据库

python - 如何从静态标签 wagtail 2.5 中的变量提供 webp

python - 如何解决 'Global name self is not defined'?

python - 使用字典和正则表达式重命名列名

python - 如何设置 Pandas 散点矩阵文本的大小和旋转?

numpy - 从 Cython 调用 PyArray_SearchSorted——3 或 4 个参数?