[英]Counting list items and storing in dataframe column corresponding to list item
[英]For each item in list L, find all of the corresponding items in a dataframe
我正在寻找解决此 Python 问题的快速解决方案:
- '对于列表 L 中的每个项目,在数据框列中找到所有相应的项目(`df [ 'col1' ])。
问题是L
和df ['col1']
可能包含重复值,并且应该返回所有重复值。
例如:
L = [1,4,1]
d = {'col1': [1,2,3,4,1,4,4], 'col2': ['a','b','c','d','e','f','g']}
df = pd.DataFrame(data=d)
所需的输出将是一个新的 DataFrame,其中 df [ 'col1' ] 包含以下值:
[1,1,1,1,4,4,4]
并相应地复制行。 请注意,1 出现了 4 次(L 中的两次 * df 中的两次)
我发现像.isin()
这样的明显解决方案不起作用,因为它们会删除重复项。
列表推导确实有效,但对于我的实际问题来说太慢了,其中len(df) = 16 million
和len(L) = 150000
):
idx = [y for x in L for y in df[df['col1'].values == x]]
res = df.loc[idx].reset_index(drop=True)
这基本上只是比较两个列表的问题(增加了一些数据帧索引难度),而Mad Physicist 的一个聪明且非常快速的解决方案几乎可以解决这个问题,除了L
中的重复项被删除(它返回[1, 4, 1, 4, 4]
在上面的例子中;即,它在df
找到重复项,但忽略了L
的重复项)。
train = np.array([...]) # my df['col1']
keep = np.array([...]) # my list L
keep.sort()
ind = np.searchsorted(keep, train, side='left')
ind[ind == keep.size] -= 1
train_keep = train[keep[ind] == train]
我会很感激任何想法。
初始数据:
L = [1,4,1]
df = pd.DataFrame({'col':[1,2,3,4,1,4,4] })
您可以从 L 创建数据框
df2 = pd.DataFrame({'col':L})
并将其与初始数据帧合并:
result = df.merge(df2, how='inner', on='col')
print(result)
结果:
col
0 1
1 1
2 1
3 1
4 4
5 4
6 4
IIUC尝试:
L = [1,4,1]
pd.concat([df.loc[df['col'].eq(el), 'col'] for el in L], axis=0)
(不知道你想如何拥有索引 - 以上将返回一些原始格式)
输出:
0 1
4 1
3 4
5 4
6 4
0 1
4 1
Name: col, dtype: int64
重新索引:
pd.concat([df.loc[df['col'].eq(el), 'col'] for el in L], axis=0).reset_index(drop=True)
#output:
0 1
1 1
2 4
3 4
4 4
5 1
6 1
Name: col, dtype: int64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.