gpt4 book ai didi

python - Pandas 与 Numpy 索引 : Why this fundamental difference in ordering of indices?

转载 作者:行者123 更新时间:2023-12-01 10:17:46 25 4
gpt4 key购买 nike

NumPy :

import numpy as np
nparr = np.array([[1, 5],[2,6], [3, 7]])
print(nparr)
print(nparr[0]) #first choose the row
print(nparr[0][1]) #second choose the column

给出预期的输出:
[[1 5]
[2 6]
[3 7]]

[1 5]

5

Pandas :

df = pd.DataFrame({
'a': [1, 2, 3],
'b': [5, 6, 7]
})
print(df)
print(df['a']) #first choose the column !!!
print(df['a'][1]) #second choose the row !!!

给出以下输出:
   a  b
0 1 5
1 2 6
2 3 7

0 1
1 2
2 3
Name: a, dtype: int64

2

将 Pandas 数据框中“索引”的默认顺序更改为列第一的根本原因是什么?这种一致性/直觉性的丧失对我们有什么好处?

当然,如果我使用 iloc我们可以编写类似于 Numpy 数组索引的函数:

print(df)
print(df.iloc[0]) # first choose the row
print(df.iloc[0][1]) # second choose the column
   a  b
0 1 5
1 2 6
2 3 7

a 1
b 5
Name: 0, dtype: int64

5

最佳答案

因为 Numpy 的直觉是数学(更具体地说是矩阵,类似于 MATLAB),而 Pandas 是数据库(类似于 SQL)。 Numpy 按行和列(行在前,因为矩阵的元素 (i, j) 表示第 i 行和 j 第列),而 Pandas 基于数据库的列工作,您可以在其中选择元素,即行。当然,您可以使用 iloc 直接处理索引。 ,正如你所说。

希望两者在范式/哲学上的差异是有道理的。

关于python - Pandas 与 Numpy 索引 : Why this fundamental difference in ordering of indices?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59525292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com