python - python中的函数用于在大文件中搜索特定名称的可能组合

标签 python string pandas join group-by

我有一个巨大的文件(50,000 行),有 2 列(id 和名称)。一个 id 可以有不同的名称,但我只是在寻找特定的名称及其 id。这个特定的名称可能相互之间有任何组合,我需要检查整个文件以查找它们组合在一起的任何可能的组合。 我编写了以下函数,它没有给我错误,但它也不起作用。

我还想计算这些名称的任意组合。

顺便说一句,我正在使用 pandas 并将数据作为数据框导入。

例如:

id  name
a    TD
a    NB
a    LB
b    LR
b    NB
c    LR
c    NB
d    LB

我想要的结果如下:

a  TD,NB,LR  # they might have any combination I just wrote them as example
b  NB,LR
c  NB,LR
d  LB

为了计数我想要:

TD,NB,LR 1
NB,LR    2
LB       1


def Gene_count(df_file):
    df_group_id = df.groupby('id').name
    for j in df_group_id:
            j = df.id
    for i in df_group_id:
    if i == 'TD' or i=='NB' or i=='LR' or i== 'LB':
                 print(i,j)

谢谢

最佳答案

您可以先使用groupby申请加入:

df1 = df.groupby('id')['name'].apply(','.join)
print (df1)
id
a    TD,NB,LB
b       LR,NB
c       LR,NB
d          LB
Name: name, dtype: object

然后value_counts :

print (df1.value_counts())
LR,NB       2
LB          1
TD,NB,LB    1
Name: name, dtype: int64

如果想过滤串联输出中的某些值,请使用 containsjoin | (正则表达式 or)和 boolean indexing :

df1 = df.groupby('id')['name'].apply(','.join)

df2 = df1[df1.str.contains('|'.join(['LR','NB']))]
print (df2)
id
a    TD,NB,LB
b       LR,NB
c       LR,NB
Name: name, dtype: object

print (df2.value_counts())
LR,NB       2
TD,NB,LB    1
Name: name, dtype: int64

另一种可能的解决方案是使用 double isin 进行过滤。 :

#get all id where is value LR or NB (unique is for better performance)
ids = df.loc[df.name.isin(['LR','NB']), 'id'].unique()
print (ids)
['a' 'b' 'c']

#filter by ids
df3 = df[df.id.isin(ids)]
print (df3)
  id name
0  a   TD
1  a   NB
2  a   LB
3  b   LR
4  b   NB
5  c   LR
6  c   NB

df4 = df3.groupby('id')['name'].apply(','.join)
print (df4)
id
a    TD,NB,LB
b       LR,NB
c       LR,NB
Name: name, dtype: object

print (df4.value_counts())
LR,NB       2
TD,NB,LB    1
Name: name, dtype: int64

我对这两种解决方案的性能非常感兴趣 - 它们是相同的:

np.random.seed(123)
N = 1000000
L1 = list("abcdefghijklmnopqrstuvwxyz")
df = pd.DataFrame({'id':np.random.choice(L1, N), 
                   'name': np.random.choice(L1, N)})

In [31]: %timeit (df.groupby('id')['name'].apply(','.join))
10 loops, best of 3: 130 ms per loop

In [32]: %timeit (df.groupby('id')['name'].apply(lambda x: ','.join(x.tolist())))
10 loops, best of 3: 131 ms per loop

关于python - python中的函数用于在大文件中搜索特定名称的可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40881281/

相关文章:

做 `if x in y where x.attr == val` 的 Pythonic 方式?

python - 如何使用 pyqt5 在模型/ View qml 中查看我的数据

Python - 一个字符串列在另一列中吗?

java - 每次访问都需要解释 Java 或 Ruby?

Java 字符串引用

python - write() 参数必须是 str,而不是 bytes

python - 计算列表中具有相同值的子列表

python - 将数据框中的列值拆分为空列值

python - 使用其他数据帧值添加到 pandas 数据帧中的日期

python - 蓝牙服务器接收到错误的文本数据 RFCOMM