python - df[x]、df[[x]]、df ['x' ]、df[['x' ]] 和 df.x 之间的区别

标签 python pandas dataframe series

努力理解标题中 5 个示例之间的区别。系列与数据框有一些用例吗?什么时候应该使用一个而不是另一个?哪些是等价的?

最佳答案

  1. df[x] — 使用变量 x 索引列。返回 pd.Series
  2. df[[x]] — 使用变量 x 对单列 DataFrame 进行索引/切片。返回 pd.DataFrame
  3. df['x'] — 索引名为“x”的列。返回 pd.Series
  4. df[['x']] — 对只有一个名为“x”的列的单列 DataFrame 进行索引/切片。返回 pd.DataFrame
  5. 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

进一步阅读
Indexing and Selecting Data

关于python - df[x]、df[[x]]、df ['x' ]、df[['x' ]] 和 df.x 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50302180/

相关文章:

python - 删除行并替换 pandas 中的字符

sql - 格式pandas.Timestamp用于SQLite查询

python - 奇怪的 .txt 报告到 Pandas 数据框中

r - 将分组平均值添加到数据框中的列

python - 正则表达式 python 不会像我想要的那样工作

python - 为什么在mac上使用PyQt5不能添加图标?

R 使用行数向量将数据帧分解为列表

r - 关于操作数据框的基本 R 问题

python - 如何使用 Python 将 .pptx 转换为 .pdf

Python 改变 repr float 数字