在 Pandas 中,DataFrame 就像是一个包含行和列的表格。有时候,我们需要提取单列来分析或修改特定数据。这在过滤、计算或可视化等任务中非常有帮助。当我们选择一列时,它会变成一个 Pandas Series(序列),这是一种保留标签并允许高效数据操作的一维数据结构。
目录
使用 dataframe[column_name]
这是选择单列最常用且直接的方法。我们将列名作为键放在 方括号 内传递。
Python
CODEBLOCK_25049908
输出
!dataframe使用 dataframe[column_name]
解释:这里,df[‘Interest‘] 将“Interest”列作为一个 Pandas Series 检索出来。当列名包含空格或特殊字符时,这种方法非常有用。
目录
- 使用 dataframe.column_name (点表示法)
- 使用 dataframe.loc[:, column_name]
- 使用 get()
使用 dataframe.column_name (点表示法)
这种方法使用 点表示法,提供了一种更简洁、可读性更强的写法。
Python
CODEBLOCK_d618379c
!dataframe-column-name使用 dataframe.column_name
解释: df.Interest 直接访问“Interest”列。然而,这种方法仅在列名不包含空格或特殊字符时才有效。
使用 dataframe.loc[:, column_name]
[.loc[] 方法](https://www.geeksforgeeks.org/python/python-pandas-dataframe-loc/) 允许我们通过显式指定行和列的选择来进行操作。
Python
CODEBLOCK_155140ba
输出
!dataframe-loc使用 dataframe.loc
解释: df.loc[:, ‘Interest‘] 选择了所有行 (:) 和特定的列 (‘Interest‘)。当处理多个选择和过滤条件时,这种方法非常有用。
使用 get()
.get() 方法 是另一种安全检索列的替代方式。
Python
CODEBLOCK_15d72161
输出
!get-method使用 get()
解释:df.get(‘Age‘) 获取“Age”列。如果列不存在,它将返回 None 而不是引发错误,这在某些情况下是一种更安全的方法。