2013-07-03 138 views
1

我有以下pd.DataFrame:使用从字典键过滤一个数据帧大熊猫

AllData = 
[email protected] [email protected] [email protected] [email protected] [email protected] 
1  8  3  3  8 
4  4  7  4  3 
6  8  9  1  6 
3  4  5  6  1 
7  6  0  8  1 

而且我想创建一个只有名字出现在下面的字典键的列的新pd.DataFrame :

my_dict={[email protected] : value1, [email protected] : value2, [email protected] : value5} 

因此,新的数据帧将是:

FilteredData = 
[email protected] [email protected] [email protected] 
    1  3  3 
    4  7  4 
    6  9  1 
    3  5  6 
    7  0  8 

什么是最effici这样做的方式?

我曾尝试使用:

FilteredData = AllData.filter(regex=my_dict.keys) 

,但勿庸置疑,这没有奏效。任何建议/意见欢迎

干杯,亚历克斯

回答

1

你也可以做到这一点没有过滤器的方法与此相似:

FilteredData = AllData[my_dict.keys()] 
+0

这两种方法的执行方式有什么不同吗? – user1083734

+0

我实际上并不确定在这个场景背后会发生什么变化,但是这里肯定有人必须这样做? – bdiamante

1

大熊猫dataframes有一个方法叫做过滤器,将返回一个新的数据帧。试试这个

FilteredData = AllData.filter(items=my_dict.keys()) 
+0

没有我的意思'items'到itmes,但我明白你在说什么。 – John

+0

此方法与@bdiamante提议的方法有什么区别? – user1083734

+0

@ user1083734有差异,但我对大熊猫比较陌生,不认为我可以很好地解释它们。你可以看看Github上的DataFrame源代码,并亲自查看。 ['__getitem__'](https://github.com/pydata/pandas/blob/master/pandas/core/frame.py#L1986)是bdiamante使用的“魔术”方法,[filter](https:/ /github.com/pydata/pandas/blob/master/pandas/core/frame.py#L3005)是我使用的方法。 – John