如何将列和行的pandas DataFrame子集转换为numpy数组? - python

我想知道是否有一种更简单,更节省内存的方法来从pandas DataFrame中选择行和列的子集。

例如,给定此数据框:

df = DataFrame(np.random.rand(4,5),列= list('abcde'))
打印df

a b c d e
0 0.945686 0.000710 0.909158 0.892892 0.326670
1 0.919359 0.667057 0.462478 0.008204 0.473096
2 0.976163 0.621712 0.208423 0.980471 0.048334
3 0.459039 0.788318 0.309892 0.100539 0.753992

我只希望其中列'c'的值大于0.5的那些行,但是对于那些行,我只需要列'b'和'e'。

这是我想出的方法-也许有更好的“熊猫”方式?

locs = [df.columns.get_loc(_)in ['a','d']]中的_
打印df [df.c> 0.5] [位置]

广告
0 0.945686 0.892892

我的最终目标是将结果转换为numpy数组以传递给sklearn回归算法,因此我将使用上面的代码,如下所示:

training_set = array(df [df.c> 0.5] [位置])

...这让我很烦,因为我最终在内存中存储了一个巨大的数组副本。也许还有更好的方法吗?

参考方案

.loc同时接受行和列选择器(.ix/.iloc FYI也是如此)
这也可以通过一次完成。

In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))

In [2]: df
Out[2]: 
          a         b         c         d         e
0  0.669701  0.780497  0.955690  0.451573  0.232194
1  0.952762  0.585579  0.890801  0.643251  0.556220
2  0.900713  0.790938  0.952628  0.505775  0.582365
3  0.994205  0.330560  0.286694  0.125061  0.575153

In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]: 
          a         d
0  0.669701  0.451573
1  0.952762  0.643251
2  0.900713  0.505775

并且,如果您想要这些值(尽管它应该直接传递给sklearn);框架支持阵列接口

In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]: 
array([[ 0.66970138,  0.45157274],
       [ 0.95276167,  0.64325143],
       [ 0.90071271,  0.50577509]])

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…