Select Columns in Pandas: A Complete Guide
To read specific columns using pandas, you can use the DataFrame’s [] operator to specify the column name or index position. Here is an example:
import pandas as pd
# 创建一个示例DataFrame
data = {'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]}
df = pd.DataFrame(data)
# 读取指定列名的列
column_A = df['A']
print(column_A)
# 读取指定索引位置的列
column_1 = df.iloc[:, 1]
print(column_1)
In the example above, a DataFrame with 3 columns was first created. Then the column named ‘A’ was accessed using df[‘A’], and the column at index position 1 was accessed using df.iloc[:, 1].