如何通过另一个数据框中的键来筛选数据框中的列

huangapple go评论69阅读模式
英文:

How do I filter columns in a dataframe by the keys in another dataframe

问题

我的第一个数据框架是

obj1 obj2 obj3
 01   02   03
 02   03   04

另一个数据框架是:

col1 col2 col3
obj1  M    N
obj2  M    T
obj3  M    N

我只想要第一个数据框架中被标记为

{'col2':M, 'col3':N}

的列。

所需的结果是

obj1 obj3
 01   03
 02   04

我似乎无法以合适的方式实现这一点。

英文:

My first dataframe is

obj1 obj2 obj3
 01   02   03
 02   03   04

another dataframe is:

col1 col2 col3
obj1  M    N
obj2  M    T
obj3  M    N

I only want the columns in the first dataframe who are marked with

{'col2':M, 'col3':N}

The wanted result is

obj1 obj3
 01   03
 02   04

I can't seem to achieve this in a decent way.

答案1

得分: 2

以下是翻译好的部分:

一种方法是将字典转换为一行DataFrame,然后使用merge函数进行合并,因为没有指定on参数,它将根据字典键的所有列名的交集进行合并(在辅助DataFrame中):

d = {'col2':'M', 'col3':'N'}

vals = pd.DataFrame([d]).merge(df2)['col1']

或者使用字典推导式和DataFrame.query

vals = df2.query(' & '.join(['{}=={}'.format(i,repr(j)) for i, j in d.items()]))['col1']

然后通过Index.isinDataFrame.loc进行筛选,:表示所有行:

df = df1.loc[:, df1.columns.isin(vals)]
print (df)
  obj1 obj3
0   01   03
1   02   04
英文:

One idea is convert dictionary to one row DataFrame and merge, because no parameter on it merging by intersection of all columns names (in helper DataFrame by keys of dictionary):

d = {'col2':'M', 'col3':'N'}

vals = pd.DataFrame([d]).merge(df2)['col1']

Or use DataFrame.query with dict comprehension:

vals = df2.query(' & '.join(['{}=={}'.format(i,repr(j)) 
                              for i, j in d.items()]))['col1']

And then filter by Index.isin and DataFrame.loc, : means all rows:

df = df1.loc[:, df1.columns.isin(vals)]
print (df)
  obj1 obj3
0   01   03
1   02   04

huangapple
  • 本文由 发表于 2020年1月6日 18:47:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定