pandas从列中提取排列的对值



我有一个数据框架:

df = pd.DataFrame({'start': [50, 100, 50000, 50030, 100000],
'end': [51, 101, 50001, 50031, 100001],
'value': [1, 2, 3, 4, 5]},
index=['id1', 'id2', 'id3', 'id4', 'id5'])

x       y          z
id1           foo     bar        1
id2           bar     me         2
id3           you     bar        3
id4           foo     you        4
id5           bar     foo        5

和一个排列列表:

l = [(foo, bar), (bar, foo)]

我想提取包含列[x,y]中排列的所有行:

(foo, bar) -> id1, foo, bar, 1
(bar, foo) -> id5, bar, foo, 5

我如何提取这些行依赖于两个值?

您可以将x,y列转换为MultiIndex,因此可以将Index.isinboolean indexing的值进行比较:

l = [('foo', 'bar'), ('bar', 'foo')]
df1 = df[df.set_index(['x','y']).index.isin(l)]
print (df1)
x    y  z
id1  foo  bar  1
id5  bar  foo  5

试试这个:

https://stackoverflow.com/a/16068497/1021819后,

df['xy'] = list(zip(df.x, df.y))

这将给你一列元组(x,y)

然后使用.isin()(参见https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.isin.html)

isin=df.xy.isin(l)
display(df[isin])

变! !

最新更新