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

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

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

问题

我的第一个数据框架是

  1. obj1 obj2 obj3
  2. 01 02 03
  3. 02 03 04

另一个数据框架是:

  1. col1 col2 col3
  2. obj1 M N
  3. obj2 M T
  4. obj3 M N

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

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

的列。

所需的结果是

  1. obj1 obj3
  2. 01 03
  3. 02 04

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

英文:

My first dataframe is

  1. obj1 obj2 obj3
  2. 01 02 03
  3. 02 03 04

another dataframe is:

  1. col1 col2 col3
  2. obj1 M N
  3. obj2 M T
  4. obj3 M N

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

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

The wanted result is

  1. obj1 obj3
  2. 01 03
  3. 02 04

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

答案1

得分: 2

以下是翻译好的部分:

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

  1. d = {'col2':'M', 'col3':'N'}
  2. vals = pd.DataFrame([d]).merge(df2)['col1']

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

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

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

  1. df = df1.loc[:, df1.columns.isin(vals)]
  2. print (df)
  3. obj1 obj3
  4. 0 01 03
  5. 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):

  1. d = {'col2':'M', 'col3':'N'}
  2. vals = pd.DataFrame([d]).merge(df2)['col1']

Or use DataFrame.query with dict comprehension:

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

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

  1. df = df1.loc[:, df1.columns.isin(vals)]
  2. print (df)
  3. obj1 obj3
  4. 0 01 03
  5. 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:

确定