Qua*_*sto 5 python pandas python-polars
我的数据框包含带有列表元素的b列,我需要创建c列来计算列表中每一行的元素数量。这是 Pandas 中的玩具示例:
import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b':[[1,2,3], [2], [5,0]]})
a b
0 1 [1, 2, 3]
1 2 [2]
2 3 [5, 0]
df.assign(c=df['b'].str.len())
a b c
0 1 [1, 2, 3] 3
1 2 [2] 1
2 3 [5, 0] 2
Run Code Online (Sandbox Code Playgroud)
这是我在 Polars 中的等效项:
import polars as pl
dfp = pl.DataFrame({'a': [1,2,3], 'b':[[1,2,3], [2], [5,0]]})
dfp.with_columns(pl.col('b').apply(lambda x: len(x)).alias('c'))
Run Code Online (Sandbox Code Playgroud)
我有一种感觉,这.apply(lambda x: len(x))不是最佳状态。
在 Polars 中有更好的方法吗?
您可以使用.list.len()
\ndf.with_columns(c = pl.col("b").list.len())\nRun Code Online (Sandbox Code Playgroud)\nshape: (3, 3)\n\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x90\n\xe2\x94\x82 a \xe2\x94\x86 b \xe2\x94\x86 c \xe2\x94\x82\n\xe2\x94\x82 --- \xe2\x94\x86 --- \xe2\x94\x86 --- \xe2\x94\x82\n\xe2\x94\x82 i64 \xe2\x94\x86 list[i64] \xe2\x94\x86 u32 \xe2\x94\x82\n\xe2\x95\x9e\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xaa\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xaa\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xa1\n\xe2\x94\x82 1 \xe2\x94\x86 [1, 2, 3] \xe2\x94\x86 3 \xe2\x94\x82\n\xe2\x94\x82 2 \xe2\x94\x86 [2] \xe2\x94\x86 1 \xe2\x94\x82\n\xe2\x94\x82 3 \xe2\x94\x86 [5, 0] \xe2\x94\x86 2 \xe2\x94\x82\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xb4\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xb4\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x98\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2145 次 |
| 最近记录: |