df [x],df [[x]],df ['x'],df [['x']]和df.x之间的差异

use*_*780 5 python series dataframe pandas

苦苦挣扎,了解标题中5个例子之间的区别.是系列与数据框架的一些用例吗?应该何时使用另一个?哪个是等价的?

cs9*_*s95 8

  1. df[x]- 使用变量索引列x.返回pd.Series
  2. df[[x]]- 使用变量索引/切片单列DataFrame x.返回pd.DataFrame
  3. df['x'] - 索引名为"x"的列.返回pd.Series
  4. df[['x']] - 索引/切片只有一列名为"x"的单列DataFrame.返回pd.DataFrame
  5. df.x-点访问符号,相当于df['x'](有,但是,限制什么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'
Run Code Online (Sandbox Code Playgroud)

例子

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

df[[x]]

   ID
0   0
1   1
2   2
3   3
4   4
5   5

type(df[[x]])
pandas.core.frame.DataFrame
Run Code Online (Sandbox Code Playgroud)

df[['x']]

    x
0   0
1  15
2   0
3   0
4   0
5  15

type(df[['x']])
pandas.core.frame.DataFrame
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

进一步阅读
索引和选择数据