我不太明白pandas的行(数据帧)如何用系列表示。
我知道 pandas 系列的底层表示是 numpy 数组。这意味着具有同质值的数组。我理解为什么 pandas 的 dataframe 列由系列表示(dataframe 的列代表不同实体的某些属性,即该属性的值属于相同的数据类型)。
但是这行数据框(即具有不同数据类型的潜在不同属性集)如何可以用系列表示?
我只是猜测所有这些不同属性的值都由更抽象的数据类型表示,例如“对象”,而底层(同质)numpy 数组是“对象”数组。
有人可以确认我的理解是否正确吗?
谢谢
托马斯
最佳答案
在内部,pandas
表示具有特定数据类型或dtype
的数据的每个系列或列:
df = pd.DataFrame([[2, True, 3.5, 'hello'], [4, False, 5.12, 'again']])
print(df)
0 1 2 3
0 2 True 3.50 hello
1 4 False 5.12 again
print(df.dtypes)
0 int64
1 bool
2 float64
3 object
dtype: object
当您请求包含混合类型的一行数据时,pandas
执行显式转换以创建一系列dtype=object
。这样的系列几乎可以容纳任何东西:
# extract first row
print(df.iloc[0])
0 2
1 True
2 3.5
3 hello
Name: 0, dtype: object
请注意,此对象
系列中有许多不同的类型。为了提高效率,您应该致力于对连续内存块中保存的序列执行操作。 int
、float
、datetime
和 bool
系列就是这种情况,但不会object
系列就是这种情况,它包含指向数据的指针而不是数据本身。
您可以从系列中获取 numpy
数组:
print(df.iloc[0].values)
array([2, True, 3.5, 'hello'], dtype=object)
但这是not the same作为常规系列:
Creating an array with
dtype=object
is different. The memory taken by the array now is filled with pointers to Python objects which are being stored elsewhere in memory (much like a Python list is really just a list of pointers to objects, not the objects themselves).
关于python - pandas 行怎么用系列来表示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50455829/