Polars 循环遍历数据集中的行

8

我正在尝试使用以下代码循环遍历 Polars 记录集:


import polars as pl

mydf = pl.DataFrame(
    {"start_date": ["2020-01-02", "2020-01-03", "2020-01-04"],
     "Name": ["John", "Joe", "James"]})

print(mydf)

│start_date  ┆ Name  │
│ ---        ┆ ---   │
│ strstr   │
╞════════════╪═══════╡
│ 2020-01-02 ┆ John  │
│ 2020-01-03 ┆ Joe   │
│ 2020-01-04 ┆ James │

for row in mydf.rows():
    print(row)

('2020-01-02', 'John')
('2020-01-03', 'Joe')
('2020-01-04', 'James')

有没有一种方法可以使用命名列而不是索引来特定地引用“Name”?在Pandas中,这看起来像:

import pandas as pd

mydf = pd.DataFrame(
    {"start_date": ["2020-01-02", "2020-01-03", "2020-01-04"],
     "Name": ["John", "Joe", "James"]})

for index, row in mydf.iterrows():
    mydf['Name'][index]

'John'
'Joe'
'James'
2个回答

11

您可以指定您希望行被命名为named

for row in mydf.rows(named=True):
    print(row)

它会给您一个字典:

{'start_date': '2020-01-02', 'Name': 'John'}
{'start_date': '2020-01-03', 'Name': 'Joe'}
{'start_date': '2020-01-04', 'Name': 'James'}

您可以调用row ['Name']
请注意:
  • 之前的版本返回的是命名元组而不是字典。
  • 使用iter_rows更节省内存。
  • 总体来说,不建议通过这种方式遍历数据。

行迭代不是最优的方法,因为底层数据以列为单位进行存储;在可能的情况下,请优先使用专用的导出/输出方法。


嗨@0x26res。感谢您抽出时间向我解释这个问题。如果我使用mydf.iterrows(),像下面这样的代码for row in mydf.iterrows(named=True): row['Name'],我会得到错误信息Traceback (most recent call last): File "<stdin>", line 2, in <module> TypeError: tuple indices must be integers or slices, not str - John Smith
我也很高兴能够通过列方法获得相同的结果,但是在Polars中并没有看到太多关于这种特定迭代方式的文档。再次感谢您的帮助。 - John Smith
1
如前所述,之前的版本返回namedtuple而不是dict。请尝试 row.Name - 0x26res
2
@JohnSmith 在 Polars 中迭代行的文档不是很好,因为这样做是极其不鼓励的,因为它基本上绕过了所有优化。这就像你买了一辆法拉利,然后问如何以非常缓慢和安静的方式驾驶它。你最终想要什么结果? - Dean MacGregor
嗨@DeanMacGregor,我有一个包含名称和日期的表。每一行都有变量,我将其“注入”到SQL中,在上述情况下,这将生成3个SQL语句并生成3个报告。由于溢出空间问题,我无法访问创建存储过程并一次性运行所有操作的权限。谢谢你的问题。 - John Smith

1
您可以使用select来实现。
names = mydf.select(['Name'])
for row in names:
    print(row)

嗨@Kien Truong。非常感谢您的快速回复。我以名称为例。实际上,我想获取日期和名称,因为这些项目将被发送到真实代码中的SQL语句,而不是此示例。表中的每一行都会生成一个单独的SQL。 - John Smith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接