Pandas中的行系列与列系列

3

行和列在数据对象中是基本相同的吗?例如,在以下示例中:

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,其中列是从0开始索引的,行是按列索引的:

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。行和列基本上是同一类型的对象吗?或者它们之间在使用方式上有什么区别?


1
一个Series是一个带有轴标签(包括时间序列)的一维ndarray,可以来自单个列或行。一个DataFrame是一个二维、大小可变、可能包含不同类型数据的表格数据。 - undefined
1
行和列基本上是同一类型的对象吗?我认为是的,对于第二个子问题,可能需要更多的澄清吗? - undefined
1个回答

2
如果查看 DataFrame 的文档:DataFrame 是一种二维标记数据结构,包含可能不同类型的列。你可以将它视为电子表格或 SQL 表格,或 Series 对象的字典。
如果查看 Series:Series 是一维带标签数组,能够容纳任何数据类型(整数、字符串、浮点数、Python 对象等)。
因此,如果按一个索引或一个列选择(且没有重复的索引值或列值),总是得到一个 Series。
我认为两种 Series(行或列 Series)之间没有太多区别,只有明显的一种用于具有不同类型列(Series)的一般 DataFrame,例如此处 - 列 ReleaseYear 由数字、整数填充,另外两列由字符串填充。
因此,如果查看 Series.dtype 数据会有所不同。对于相同类型的列,类型相同,object 明显是字符串 或整数,但对于从行中创建的 Series,则是混合类型的值,第一个值是字符串,第二个是整数,第三个是字符串。因此最终得到的是对象。如果分别使用 .apply(type) 进行测试,则可以检查它:
注意:
如果所有列具有相同的类型,则这里没有这种差异。
注意1:
当然,可以创建填充有混合数据的 Series,那么从列创建的 Series 也具有相同的对象 dtype,就像从行创建的 Series 一样。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接