python - pandas 行怎么用系列来表示?

标签 python pandas dataframe

我不太明白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

请注意,此对象系列中有许多不同的类型。为了提高效率,您应该致力于对连续内存块中保存的序列执行操作。 intfloatdatetimebool 系列就是这种情况,但不会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/

相关文章:

python - 将大文件从 .zip 存档写入 Pandas 数据帧

python - 无法从 __future__ 导入注释

Python:标记数据时出错。 C 错误:在源上调用 read(nbytes) 失败,输入 nzip 文件

python - 将 Pandas Dataframe 转换为特定格式

python - 如何在 Python 中使用猴子修补来替换特定参数?

python - 为什么朴素的字符串连接在一定长度以上会变成二次方?

python - 按总和日期分组,并用过去日期中的事故填充所有缺失值,直到计数 = 1

python - 如何使用stockstats查看MACD信号?

python - 选择特定列以计算 Pandas 中的行式总计

python - 根据另一个数据框中的列名选择数据框中的行