努力理解标题中 5 个示例之间的区别。系列与数据框有一些用例吗?什么时候应该使用一个而不是另一个?哪些是等价的?
最佳答案
df[x]
— 使用变量x
索引列。返回pd.Series
df[[x]]
— 使用变量x
对单列 DataFrame 进行索引/切片。返回pd.DataFrame
df['x']
— 索引名为“x”的列。返回pd.Series
df[['x']]
— 对只有一个名为“x”的列的单列 DataFrame 进行索引/切片。返回pd.DataFrame
df.x
— 点访问器表示法,等同于df['x']
(但是,limitations 在什么x
可以命名,如果要成功使用点符号)。返回pd.Series
使用单括号[...]
,您只能将单个列索引为系列。使用双括号 [[...]]
,您可以根据需要选择任意数量的列,这些列将作为新 DataFrame 的一部分返回。
设置
df
ID x
0 0 0
1 1 15
2 2 0
3 3 0
4 4 0
5 5 15
x = 'ID'
示例
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
关于python - df[x]、df[[x]]、df ['x' ]、df[['x' ]] 和 df.x 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50302180/