本文简要介绍
pyspark.pandas.DataFrame.transform
的用法。用法:
DataFrame.transform(func: Callable[[…], Series], axis: Union[int, str] = 0, *args: Any, **kwargs: Any) → DataFrame
调用
func
自行生成具有转换值的系列,并且其长度与其输入相同。另见Transform and apply a function。
注意
此 API 执行该函数一次以推断可能昂贵的类型,例如,在聚合或排序后创建数据集时。
为避免这种情况,请在
func
中指定返回类型,例如,如下所示:>>> def square(x) -> ps.Series[np.int32]: ... return x ** 2
pandas-on-Spark 使用返回类型提示并且不尝试推断类型。
注意
func
中的系列实际上是多个 Pandas 系列作为整个pandas-on-Spark系列的片段;因此,不能保证每个系列的长度。例如,针对每个系列的聚合确实可以作为全局聚合,但是每个段的聚合。见下文:>>> def func(x) -> ps.Series[np.int32]: ... return x + sum(x)
- func:函数
用于转换数据的函数。当 Pandas 系列通过时它必须工作。
- axis:int,默认 0 或 ‘index’
目前只能设置为0。
- *args:
要传递给 func 的位置参数。
- **kwargs:
要传递给 func 的关键字参数。
- DataFrame
DataFrame 必须与 self 具有相同的长度。
- Exception:如果返回的 DataFrame 的长度与 self 的长度不同。
参数:
返回:
抛出:
例子:
>>> df = ps.DataFrame({'A': range(3), 'B': range(1, 4)}, columns=['A', 'B']) >>> df A B 0 0 1 1 1 2 2 2 3
>>> def square(x) -> ps.Series[np.int32]: ... return x ** 2 >>> df.transform(square) A B 0 0 1 1 1 4 2 4 9
您可以省略类型提示并让pandas-on-Spark 推断其类型。
>>> df.transform(lambda x: x ** 2) A B 0 0 1 1 1 4 2 4 9
对于多索引列:
>>> df.columns = [('X', 'A'), ('X', 'B')] >>> df.transform(square) X A B 0 0 1 1 1 4 2 4 9
>>> (df * -1).transform(abs) X A B 0 0 1 1 1 2 2 2 3
您还可以指定额外的参数。
>>> def calculation(x, y, z) -> ps.Series[int]: ... return x ** y + z >>> df.transform(calculation, y=10, z=20) X A B 0 20 21 1 21 1044 2 1044 59069
相关用法
- Python pyspark DataFrame.transform用法及代码示例
- Python pyspark DataFrame.transpose用法及代码示例
- Python pyspark DataFrame.truncate用法及代码示例
- Python pyspark DataFrame.truediv用法及代码示例
- Python pyspark DataFrame.to_latex用法及代码示例
- Python pyspark DataFrame.to_delta用法及代码示例
- Python pyspark DataFrame.to_table用法及代码示例
- Python pyspark DataFrame.to_pandas用法及代码示例
- Python pyspark DataFrame.to_records用法及代码示例
- Python pyspark DataFrame.take用法及代码示例
- Python pyspark DataFrame.to_excel用法及代码示例
- Python pyspark DataFrame.toPandas用法及代码示例
- Python pyspark DataFrame.tail用法及代码示例
- Python pyspark DataFrame.to_spark_io用法及代码示例
- Python pyspark DataFrame.toLocalIterator用法及代码示例
- Python pyspark DataFrame.to_pandas_on_spark用法及代码示例
- Python pyspark DataFrame.to_clipboard用法及代码示例
- Python pyspark DataFrame.to_numpy用法及代码示例
- Python pyspark DataFrame.to_orc用法及代码示例
- Python pyspark DataFrame.to_dict用法及代码示例
- Python pyspark DataFrame.toJSON用法及代码示例
- Python pyspark DataFrame.to_parquet用法及代码示例
- Python pyspark DataFrame.to_markdown用法及代码示例
- Python pyspark DataFrame.to_csv用法及代码示例
- Python pyspark DataFrame.toDF用法及代码示例
注:本文由纯净天空筛选整理自spark.apache.org大神的英文原创作品 pyspark.pandas.DataFrame.transform。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。