我正在尝试使用以下代码循环遍历 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 │
│ --- ┆ --- │
│ str ┆ str │
╞════════════╪═══════╡
│ 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')
有没有办法使用命名列而不是索引来专门引用“名称”?在 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'
您可以指定您希望对行进行命名
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
行迭代并不是最优的,因为底层数据是以柱状形式存储的;如果可能,更喜欢通过一种专用导出/输出方法进行导出。
您可以使用
select
names = mydf.select(['Name'])
for row in names:
print(row)
在极坐标中,带有 pl.DataFrame.iter_rows
的
named=True
应优先于 pl.DataFrame.rows
,因为后者将所有帧数据具体化为行列表,这可能会很昂贵。
import polars as pl
df = pl.DataFrame({
"start_date": ["2020-01-02", "2020-01-03", "2020-01-04"],
"name": ["John", "Joe", "James"]
})
for row in df.iter_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'}