如何转换一系列 Polars 数据框?

问题描述 投票:0回答:1

我正在处理一个大型数据帧(198,619 行 x 19,110 列),因此使用 Polars 包读取 tsv 文件。熊猫需要太长的时间。

但是,我现在面临一个问题,因为我想转换每个单元格的值

x
,将其以基数 2 提高,如下所示:
2^x

我运行以下行作为示例:

df_copy = df
df_copy[:,1] = 2**df[:,1]

但我收到此错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/tmp/pbs.98503.hn-10-03/ipykernel_196334/3484346087.py in <module>
      1 df_copy = df
----> 2 df_copy[:,1] = 2**df[:,1]

~/.local/lib/python3.9/site-packages/polars/internals/frame.py in __setitem__(self, key, value)
   1845 
   1846             # dispatch to __setitem__ of Series to do modification
-> 1847             s[row_selection] = value
   1848 
   1849             # now find the location to place series

~/.local/lib/python3.9/site-packages/polars/internals/series.py in __setitem__(self, key, value)
    512             self.__setitem__([key], value)
    513         else:
--> 514             raise ValueError(f'cannot use "{key}" for indexing')
    515 
    516     def estimated_size(self) -> int:

ValueError: cannot use "slice(None, None, None)" for indexing

这应该很简单,但我无法弄清楚,因为我是 Polars 新手。

python pandas dataframe python-polars
1个回答
2
投票

利用 Polars 的速度和灵活性的秘诀是学习使用表达式。 因此,您需要避免 Pandas 风格的索引方法。

让我们从这些数据开始:

import polars as pl

nbr_rows = 4
nbr_cols = 5
df = pl.DataFrame({
    "col_" + str(col_nbr): pl.int_range(col_nbr, nbr_rows + col_nbr, eager=True)
    for col_nbr in range(0, nbr_cols)
})
df
shape: (4, 5)
┌───────┬───────┬───────┬───────┬───────┐
│ col_0 ┆ col_1 ┆ col_2 ┆ col_3 ┆ col_4 │
│ ---   ┆ ---   ┆ ---   ┆ ---   ┆ ---   │
│ i64   ┆ i64   ┆ i64   ┆ i64   ┆ i64   │
╞═══════╪═══════╪═══════╪═══════╪═══════╡
│ 0     ┆ 1     ┆ 2     ┆ 3     ┆ 4     │
│ 1     ┆ 2     ┆ 3     ┆ 4     ┆ 5     │
│ 2     ┆ 3     ┆ 4     ┆ 5     ┆ 6     │
│ 3     ┆ 4     ┆ 5     ┆ 6     ┆ 7     │
└───────┴───────┴───────┴───────┴───────┘

在 Polars 中,我们将您的计算表示为:

df_copy = df.select(pl.lit(2).pow(pl.all()).name.keep())
print(df_copy)
shape: (4, 5)
┌───────┬───────┬───────┬───────┬───────┐
│ col_0 ┆ col_1 ┆ col_2 ┆ col_3 ┆ col_4 │
│ ---   ┆ ---   ┆ ---   ┆ ---   ┆ ---   │
│ f64   ┆ f64   ┆ f64   ┆ f64   ┆ f64   │
╞═══════╪═══════╪═══════╪═══════╪═══════╡
│ 1.0   ┆ 2.0   ┆ 4.0   ┆ 8.0   ┆ 16.0  │
│ 2.0   ┆ 4.0   ┆ 8.0   ┆ 16.0  ┆ 32.0  │
│ 4.0   ┆ 8.0   ┆ 16.0  ┆ 32.0  ┆ 64.0  │
│ 8.0   ┆ 16.0  ┆ 32.0  ┆ 64.0  ┆ 128.0 │
└───────┴───────┴───────┴───────┴───────┘
© www.soinside.com 2019 - 2024. All rights reserved.