支持的时间类型如下表所示。
PyODPS支持的集合类型有List和Dict。这两个类型都可以使用下标获取集合中的某个项目。
len
方法用于获得集合的大小。
同时,两种集合均有
explode
方法,用于展开集合中的内容。对于List,
explode
默认返回一列,当传入参数
pos
时, 将返回两列,其中一列为值在数组中的编号(类似Python的
enumerate
函数)。对于Dict,
explode
会返回两列, 分别表示keys及values。
explode
中也可以传入列名,作为最后生成的列。
示例如下。
>>> df
id a b
0 1 [a1, b1] {'a2': 0, 'b2': 1, 'c2': 2}
1 2 [c1] {'d2': 3, 'e2': 4}
>>> df[df.id, df.a[0], df.b['b2']]
id a b
0 1 a1 1
1 2 c1 NaN
>>> df[df.id, df.a.len(), df.b.len()]
id a b
0 1 2 3
1 2 1 2
>>> df.a.explode()
0 a1
1 b1
2 c1
>>> df.a.explode(pos=True)
a_pos a
0 0 a1
1 1 b1
2 0 c1
>>> # 指定列名。
>>> df.a.explode(['pos', 'value'], pos=True)
pos value
0 0 a1
1 1 b1
2 0 c1
>>> df.b.explode()
b_key b_value
0 a2 0
1 b2 1
2 c2 2
3 d2 3
4 e2 4
>>> # 指定列名。
>>> df.b.explode(['key', 'value'])
key value
0 a2 0
1 b2 1
2 c2 2
3 d2 3
4 e2 4
explode
也可以和
并列多行输出
结合,以将原有列和
explode
的结果相结合,示例如下。
>>> df[df.id, df.a.explode()]
id a
0 1 a1
1 1 b1
2 2 c1
>>> df[df.id, df.a.explode(), df.b.explode()]
id a b_key b_value
0 1 a1 a2 0
1 1 a1 b2 1
2 1 a1 c2 2
3 1 b1 a2 0
4 1 b1 b2 1
5 1 b1 c2 2
6 2 c1 d2 3
7 2 c1 e2 4
除了下标
len
和
explode
两个共有方法以外,List还支持下列方法。
其它元素操作(isin,notin,cut)
isin
用于判断Sequence里的元素是否在某个集合元素里,
notin
反之。
>>> iris.sepallength.isin([4.9, 5.1]).rename('sepallength').head(5)
sepallength
0 True
1 True
2 False
3 False
4 False
cut
提供离散化的操作,可以将Sequence的数据拆成几个区段。
>>> iris.sepallength.cut(range(6), labels=['0-1', '1-2', '2-3', '3-4', '4-5']).rename('sepallength_cut').head(5)
sepallength_cut
0 None
1 4-5
2 4-5
3 4-5
4 4-5
include_under
和
include_over
可以分别包括向下和向上的区间。
>>> labels = ['0-1', '1-2', '2-3', '3-4', '4-5', '5-']
>>> iris.sepallength.cut(range(6), labels=labels, include_over=True).rename('sepallength_cut').head(5)
sepallength_cut
0 5-
1 4-5
2 4-5
3 4-5
4 4-5
调用MaxCompute内建或者已定义函数
如果您需要调用MaxCompute上的内建或者已定义函数来生成列,您可以使用
func
接口,该接口默认函数返回值为STRING,可以用
rtype
参数指定返回值。
>>> from odps.df import func
>>> iris[iris.name, func.rand(rtype='float').rename('rand')][:4]
>>> iris[iris.name, func.rand(10, rtype='float').rename('rand')][:4]
>>> # 调用ODPS上定义的UDF,列名无法确定时需要手动指定。
>>> iris[iris.name, func.your_udf(iris.sepalwidth, iris.sepallength, rtype='float').rename('new_col')]
>>> # 从其它Project调用UDF,也可通过name参数指定列名。
>>> iris[iris.name, func.your_udf(iris.sepalwidth, iris.sepallength, rtype='float', project='udf_project', name='new_col')]
说明
Pandas后端不支持执行带有
func
的表达式。