Skip to main content
 首页 » 编程设计

python之from_records() 的 nrows 参数在 pandas 中有什么作用

2024年12月31日10小虾米

我正在尝试学习如何向开源项目提交 Pull-Request。 所以我选择了issue #23455来自 Pandas 开发者。这是一个简单的文档错误。但是我意识到我不知道 nrows 在 from_records 中实际做了什么。

我试过了

sales = [('Jones LLC', 150, 200, 50), 
     ('Alpha Co', 200, 210, 90), 
     ('Blue Inc', 140, 215, 95)] 
labels = ['account', 'Jan', 'Feb', 'Mar'] 
df = pd.DataFrame.from_records(sales, columns=labels) 

产生

    account  Jan  Feb  Mar 
0  Jones LLC  150  200   50 
1   Alpha Co  200  210   90 
2   Blue Inc  140  215   95 

作为输出。但是据我了解,如果我执行以下操作:

df = pd.DataFrame.from_records(sales, columns=labels,nrows=1) 

我应该在 df 中只有一行。相反,我的输出与上面的 df 相同。

有人可以帮我解决这个问题吗?谢谢。

请您参考如下方法:

nrows 是用于选择记录的前 n 个元素的参数。如果您看到代码,它目前仅适用于迭代器。可能有一些原因为什么只在我目前不知道的迭代器上。

显示 nrows 用例的示例是将销售数据转换为迭代器。即

sales = iter([('Jones LLC', 150, 200, 50),('Alpha Co', 200, 210, 90), ('Blue Inc', 140, 215, 95)]) 
 
df = pd.DataFrame.from_records(sales,nrows=2) 
           0    1    2   3 
0  Jones LLC  150  200  50 
1   Alpha Co  200  210  90 
 
sales = iter([('Jones LLC', 150, 200, 50),('Alpha Co', 200, 210, 90), ('Blue Inc', 140, 215, 95)]) 
 
df = pd.DataFrame.from_records(sales,nrows=3) 
 
           0    1    2   3 
0  Jones LLC  150  200  50 
1   Alpha Co  200  210  90 
2   Blue Inc  140  215  95