plpython 程序中的 Greenplum pandas 数据框集成(来自数据库内部)

Posted

技术标签:

【中文标题】plpython 程序中的 Greenplum pandas 数据框集成(来自数据库内部)【英文标题】:Greenplum pandas dataframe integration in plpython procedure (from INSIDE the database) 【发布时间】:2018-07-12 12:13:01 【问题描述】:

是否可以在 greenplum 数据库中使用 pandas,如果可以,如何使用? 我在greenplum里面。我正在创建一个函数:

CREATE OR REPLACE FUNCTION myfunction() RETURNS
text AS $$ 
...
python code
...
rv = plpy.execute("SELECT * FROM mytable")
...

$$ LANGUAGE plpythonu;
SELECT public.myfunction()

命令rv = plpy.execute("SELECT * FROM mytable") 生成一个PlyResult 类型的对象。此时,我想用 python pandas 分析 rv 中的数据,例如。如何将 rv 转换为数据框? 谢谢!

【问题讨论】:

【参考方案1】:

这是我的一个例子:

drop function if exists describe_yelp();
create or replace function describe_yelp(
OUT stats text,
OUT stars numeric,
OUT cool numeric,
OUT useful numeric,
OUT funny numeric,
OUT txt_length numeric)
returns setof record
as $$
import pandas as pd
import numpy as np
import nltk
from nltk.corpus import stopwords
yelp=pd.DataFrame.from_records(plpy.execute('select * from yelp'))[['stars','cool','useful','funny','text']]
yelp['txt_length'] = yelp['text'].apply(len)
return yelp.describe().to_records()      
$$
language plpythonu;

我的博客里还有更多Greenplum - Pandas - Numpy - 等集成的例子: https://dwhsys.com/2018/05/06/data-mining-in-mpp-database/

【讨论】:

【参考方案2】:

也许你可以试试pd.DataFrame(rv[0:])。 下面是 Postgres 中的一个测试

postgres=# do $$
postgres$# import numpy as np
postgres$# import pandas as pd
postgres$# 
postgres$# iris = plpy.execute("SELECT * FROM iris LIMIT 3")
postgres$# plpy.notice(type(iris[0:]))
postgres$# iris = pd.DataFrame(iris[0:])
postgres$# 
postgres$# X = iris[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']].values
postgres$# plpy.notice(type(X))
postgres$# plpy.notice(X)
postgres$# 
postgres$# $$ language plpython3u;
NOTICE:  <class 'list'>
NOTICE:  <class 'numpy.ndarray'>
NOTICE:  [[Decimal('5.10') Decimal('3.50') Decimal('1.40') Decimal('0.20')]
 [Decimal('4.90') Decimal('3.00') Decimal('1.40') Decimal('0.20')]
 [Decimal('4.70') Decimal('3.20') Decimal('1.30') Decimal('0.20')]]
DO
postgres=# 

【讨论】:

以上是关于plpython 程序中的 Greenplum pandas 数据框集成(来自数据库内部)的主要内容,如果未能解决你的问题,请参考以下文章

Greenplum 4.3:填充缺失值

greenplum中的greenplum hadoop如何配置生成gphdfs.so

Greenplum扩容

在greenplum数据库中,我们可以从查询条件中转储表吗

Greenplum数据库中的索引和集群

Greenplum数据库中的索引和集群