努力理解标题中 5 个示例之间的区别。系列与数据框之间有一些用例吗?什么时候应该使用其中一种而不是另一种?哪些是等价的?
-
df[x]
— 使用变量索引列x
。退货pd.Series
-
df[[x]]
— 使用变量对单列 DataFrame 进行索引/切片x
。退货pd.DataFrame
-
df['x']
— 索引名为“x”的列。退货pd.Series
-
df[['x']]
— 对只有一列名为“x”的单列 DataFrame 进行索引/切片。退货pd.DataFrame
-
df.x
— 点访问器表示法,相当于df['x']
(但是,有局限性 https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access什么x
如果要成功使用点表示法,则可以命名)。退货pd.Series
带单括号[...]
您只能将单个列索引为系列。带有双括号,[[...]]
,您可以根据需要选择任意数量的列,这些列将作为新 DataFrame 的一部分返回。
Setup
df
ID x
0 0 0
1 1 15
2 2 0
3 3 0
4 4 0
5 5 15
x = 'ID'
Examples
df[x]
0 0
1 1
2 2
3 3
4 4
5 5
Name: ID, dtype: int64
type(df[x])
pandas.core.series.Series
df['x']
0 0
1 15
2 0
3 0
4 0
5 15
Name: x, dtype: int64
type(df['x'])
pandas.core.series.Series
df[[x]]
ID
0 0
1 1
2 2
3 3
4 4
5 5
type(df[[x]])
pandas.core.frame.DataFrame
df[['x']]
x
0 0
1 15
2 0
3 0
4 0
5 15
type(df[['x']])
pandas.core.frame.DataFrame
df.x
0 0
1 15
2 0
3 0
4 0
5 15
Name: x, dtype: int64
type(df.x)
pandas.core.series.Series
进一步阅读
索引和选择数据 https://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-and-selecting-data
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)