简体   繁体   English

Pandas - 如何使用另一个 dataframe 从 dataframe 中提取列?

[英]Pandas - How to extract columns from a dataframe using another dataframe?

I am looking to extract columns from a dataframe using another dataframe.我希望使用另一个 dataframe 从 dataframe 中提取列。 I don't want to hard code the column headers into the code as the data comes from a csv and columns can be added with different headers.我不想将列标题硬编码到代码中,因为数据来自 csv 并且列可以添加不同的标题。 Tried with.loc and using iterations, but nothing seems to work.尝试使用 .loc 并使用迭代,但似乎没有任何效果。 This is what I have for code which are all from two different csv documents...这就是我所拥有的代码,它们都来自两个不同的 csv 文档......

df1 = df1 =

    Date     a   b   c  d
 11/11/2011  2   3   4  5
 11/12/2011  3   4   5  6
 11/13/2011  4   5   6  7         

df1 was translated using a.pivot and a,b,c,d's column header is Symbol and df1 使用 a.pivot 和 a,b,c,d 的列 header 是符号和

df2= df2=

Symbol
    b
    d

The expect outcome is...预期的结果是...

     b   d
 x   3   5
 y   4   6
 z   5   7  

Tried doing试过做

df1.loc(df2)

but got a 'DataFrame' objects are mutable, thus they cannot be hashed error但是得到一个“DataFrame”对象是可变的,因此它们不能被散列错误

Thanks for the help!谢谢您的帮助!

You can do this:你可以这样做:

In [157]: df1[df2['Symbol']]
Out[157]: 
   b  d
0  3  5
1  4  6
2  5  7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM