【问题标题】:Row Series vs Col Series in PandasPandas 中的行系列与列系列
【发布时间】:2020-08-16 05:10:35
【问题描述】:

行和列是否本质上与数据对象相同?例如,在下面:

import pandas as pd
df = pd.DataFrame([
    {"Title": "Titanic",    "ReleaseYear": 1997, "Director": "James Cameron"},
    {"Title": "Spider-Man", "ReleaseYear": 2002, "Director": "Sam Raimi"}
]
title_column = df['Title']
print(title_column)
print (type(title_column))

row_one = df.loc[0]
print(row_one)
print (type(row_one))

它们都返回 Series,其中 Column 以 0 为索引,而 Row 以 Column 为索引:

0       Titanic
1    Spider-Man
Name: Title, dtype: object
<class 'pandas.core.series.Series'>

Title                Titanic
ReleaseYear             1997
Director       James Cameron
Name: 0, dtype: object
<class 'pandas.core.series.Series'>

然后,一旦选择了多个列或行,它就会变成DataFrame。 Row 和 Column 基本上是同一类型的对象,或者它们之间有什么区别,在使用方式上?

【问题讨论】:

  • A Series 是一个带有轴标签(包括时间序列)的一维ndarray,无论是来自单列还是单行。 DataFrame 是一个二维、大小可变、可能异构的表格数据。
  • Are the Row and Column basically the same type of object - 我认为是的,第二个子问题可能更清楚?

标签: python pandas dataframe


【解决方案1】:

如果检查DataFrame 的文档:

DataFrame 是一种二维标记数据结构,具有可能不同类型的列。您可以将其视为电子表格或 SQL 表,或 Series 对象的字典

如果检查Series:

Series 是一个带标签的一维数组,能够保存任何数据类型(整数、字符串、浮点数、Python 对象等)。

因此,如果按一个索引或一列(而不是重复的索引值或列值)选择,则始终得到Series。

我认为这两个系列(行或列系列)之间没有太多区别,显然只有一个对于一般DataFrame 具有不同类型的列(Series),就像这里一样 - 列ReleaseYear 由数字、整数填充,另外两列都用字符串填充。

因此,如果检查Series.dtype 的数据会有所不同。对于列是相同类型,object what is obviously strings 或整数,但对于来自行的系列是混合类型的值,第一个值是字符串,第二个整数和第三个字符串。所以最终得到对象。如果可以通过.apply(type) 单独测试,请检查:

通知:

如果所有列都具有相同的类型,那么这里没有这种区别。

通知1:

当然,可以创建由混合数据填充的系列,然后从列创建的系列的对象 dtype 与从行创建的系列相同。

year_column = df['ReleaseYear']
print(year_column)
0    1997
1    2002
Name: ReleaseYear, dtype: int64

print (type(year_column))
<class 'pandas.core.series.Series'>

print (year_column.dtype)
int64

print (year_column.apply(type))
0    <class 'int'>
1    <class 'int'>
Name: ReleaseYear, dtype: object

row_one = df.loc[0]
print(row_one)
Title                Titanic
ReleaseYear             1997
Director       James Cameron
Name: 0, dtype: object

print (type(row_one))
<class 'pandas.core.series.Series'>

print (row_one.dtype)
object

print (row_one.apply(type))
Title                  <class 'str'>
ReleaseYear    <class 'numpy.int64'>
Director               <class 'str'>
Name: 0, dtype: object

【讨论】:

    猜你喜欢
    • 2014-08-12
    • 2015-09-02
    • 2019-08-03
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 2014-07-24
    相关资源
    最近更新 更多