我有 2 个数据帧 df
和 table
:
import pandas as pd
df = pd.DataFrame({'A':[0,2,6,3,6,8,9,2,1,0],
'B':[1,1,1,1,3,3,5,5,5,2]})
table = pd.DataFrame({'A':[[0,4],[5,10],[2,8],[9,10],[0,8],[9,10],[5,10],[0,4],[1,7],[8,10]],
'B':[1,1,2,2,3,3,4,4,5,5],
'C':[[1,2,3],[4,5,6],[7,8],[9],[10,11,12],[13,14],[15],[16,17],[18,19,20],[21,22,23,24]]})
我的目标是只要满足以下条件,就打印 table['C']
通用行的内容:
df['B']
的 item 等于table['B']
df['A']
的项目属于table['A']
范围
我能够通过使用以下代码行来实现我的目标:
for i,row1 in df.iterrows():
for j, row2 in table.iterrows():
if row1['B'] == row2['B'] and (row1['A'] in range(row2['A'][0],row2['A'][1])):
print(row2['C'])
我想知道是否有可能以更高效、更优雅的方式获得相同的结果,因为 df
和 table
可能非常大。
最佳答案
您可以使用merge
用于按B
列创建所有组合,然后apply
用于创建 bool 掩码
,最后按boolean indexing
进行过滤:
df1 = pd.merge(df, table, on='B')
df1 = df1[df1.apply(lambda x: x.A_x in range(x['A_y'][0],x['A_y'][1]), axis=1)]
print(df1)
A_x B A_y C
0 0 1 [0, 4] [1, 2, 3]
2 2 1 [0, 4] [1, 2, 3]
5 6 1 [5, 10] [4, 5, 6]
6 3 1 [0, 4] [1, 2, 3]
8 6 3 [0, 8] [10, 11, 12]
13 9 5 [8, 10] [21, 22, 23, 24]
14 2 5 [1, 7] [18, 19, 20]
16 1 5 [1, 7] [18, 19, 20]
关于python - 如果不同数据帧的项目相等但尊重 Pandas 的条件,则打印值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42901752/