作为来自 pandas 的 Polars 新用户,我搜索了 Polars GitHub 页面、用户指南、stackoverflow 和不和谐频道,了解如何向 Polars 数据框添加新列。我只找到了关于如何在现有列的基础上添加新列的极坐标示例。
下面的 pandas 示例应该如何转换为 Polars 语法?
import pandas as pd
df = pd.DataFrame({'existing_column': [1, 2, 3]})
df['new_column'] = "some text"
Run Code Online (Sandbox Code Playgroud)
最终数据帧的预期内容:
| 现有列 | 新列 |
|---|---|
| 1 | 一些文本 |
| 2 | 一些文本 |
| 3 | 一些文本 |
假设我的数据如下所示:
data = {
'value': [1,9,6,7,3, 2,4,5,1,9]
}
Run Code Online (Sandbox Code Playgroud)
对于每一行,我想找到比当前元素大的最新前一个元素的行号。
所以,我的预期输出是:
[None, 0, 1, 2, 1, 1, 3, 4, 1, 0]
Run Code Online (Sandbox Code Playgroud)
1没有前一个元素,所以我想None在结果中9至少比它之前的所有元素一样大,所以我想0在结果中6前一个元素9比它大。他们之间的距离是1。所以,我想要1在这里的结果。我知道我可以在 Python 中循环执行此操作(如果我编写扩展,则可以在 C/Rust 中)。
我的问题:是否可以完全使用数据帧操作来解决这个问题?熊猫或者北极熊,都可以。但仅限数据帧操作。
因此,请不要执行以下操作:
applymap_elementsmap_rowsiter_rows我知道如何将函数应用于Pandas-DataFrame中存在的所有列。但是,我还没有弄清楚如何在使用Polars-DataFrame时实现这一点。
我查看了《Polars 用户指南》中专门讨论此主题的部分,但我还没有找到答案。在这里,我附上了我不成功的尝试的代码片段。
import numpy as np
import polars as pl
import seaborn as sns
# Loading toy dataset as Pandas DataFrame using Seaborn
df_pd = sns.load_dataset('iris')
# Converting Pandas DataFrame to Polars DataFrame
df_pl = pl.DataFrame(df_pd)
# Dropping the non-numeric column...
df_pd = df_pd.drop(columns='species') # ... using Pandas
df_pl = df_pl.drop('species') # ... using Polars
# Applying function to the whole DataFrame...
df_pd_new = df_pd.apply(np.log2) # ... using Pandas
# df_pl_new …Run Code Online (Sandbox Code Playgroud) 有没有与极坐标中的 df.groupby().shift 等效的方法?在组内使用 pandas.shift()
我无法将极坐标数据帧与 scikitlearn 一起使用进行机器学习训练。
目前,我正在极坐标中进行所有数据帧预处理,并且在模型训练期间,我将其转换为 pandas 数据帧,以便它能够工作。
有没有什么方法可以直接使用 Polars 数据帧进行 ML 训练而不将其更改为 pandas?
如何比较两个极坐标DataFrames的值是否相等?看起来==只有当两个表是同一个对象时才是正确的:
import polars as pl
pl.DataFrame({"x": [1,2,3]}) == pl.DataFrame({"x": [1,2,3]}) # False
Run Code Online (Sandbox Code Playgroud) 我需要在数据框中创建一个新列来存储处理后的值。所以我使用了 Polars apply 函数对 dicom 进行一些处理,然后返回值。但此应用函数默认将整列视为极坐标系列,并且不会逐行处理。
df = df.with_columns(
[
pl.apply(
exprs=["Filename", "Dicom_Tag", "Dicom_Tag_Corrected", "Name"],
f=apply_corrections_polars,
).alias("dicom_tag_value_corrected"),
]
)
Run Code Online (Sandbox Code Playgroud) 我有一个极坐标数据框,其中有许多系列,如下所示:
pl.Series(['cow', 'cat', '', 'lobster', ''])
Run Code Online (Sandbox Code Playgroud)
我希望他们成为
pl.Series(['cow', 'cat', pl.Null, 'lobster', pl.Null])
Run Code Online (Sandbox Code Playgroud)
简单的字符串替换不起作用,因为pl.Null不是类型PyString:
pl.Series(['cow', 'cat', '', 'lobster', '']).str.replace('', pl.Null)
Run Code Online (Sandbox Code Playgroud)
Series在极地中对/执行此操作的惯用方法是什么DataFrame?
在 pandas 中,它会自动发生,只需通过调用pd.concat([df1, df2, df3]),之前没有该列的框架就会获得一个填充有NaNs 的列。
在极坐标中,我收到一条'shape error'消息,表明列不同(11 列df1vs 12 列df2)。
我想知道如何将 Spark 数据帧转换为 Polars 数据帧。
假设我在 PySpark 上有这段代码:
df = spark.sql('''select * from tmp''')
Run Code Online (Sandbox Code Playgroud)
我可以使用 轻松将其转换为 pandas 数据框.toPandas。极坐标中有类似的东西吗,因为我需要获取极坐标数据帧以进行进一步处理?
python-polars ×10
python ×6
apply ×2
pandas ×2
append ×1
dataframe ×1
pyspark ×1
scikit-learn ×1