有三种基本方法可以用来选择pandas DataFrame的多个列。
方法1:通过索引选择列
df_new = df.iloc[:, [0,1,3]]
方法2:在索引范围内选择列
df_new = df.iloc[:, 0:3]
方法3:按名称选择列
df_new = df[['col1', 'col2']]
下面的例子展示了如何在下面的pandas DataFrame中使用每种方法:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
'assists': [5, 7, 7, 9, 12, 9, 9, 4],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12],
'blocks': [4, 7, 7, 6, 5, 8, 9, 10]})
#view DataFrame
df
points assists rebounds blocks
0 25 5 11 4
1 12 7 8 7
2 15 7 10 7
3 14 9 6 6
4 19 12 6 5
5 23 9 5 8
6 25 9 9 9
7 29 4 12 10
方法1:通过索引选择列
下面的代码显示了如何选择索引位置0、1和3的列:
#select columns in index positions 0, 1, and 3
df_new = df.iloc[:, [0,1,3]]
#view new DataFrame
df_new
points assists blocks
0 25 5 4
1 12 7 7
2 15 7 7
3 14 9 6
4 19 12 5
5 23 9 8
6 25 9 9
7 29 4 10
请注意,索引位置0、1和3的列被选中。
注意:pandas DataFrame中的第一列位于0的位置。
方法2:选择索引范围内的列
下面的代码显示了如何选择索引范围内的列0到3:
#select columns in index range 0 to 3
df_new = df.iloc[:, 0:3]
#view new DataFrame
df_new
points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6
5 23 9 5
6 25 9 9
7 29 4 12
请注意,位于该范围内最后一个值(3)的列将不包括在输出中。
方法3:通过名称选择列
下面的代码显示了如何按名称选择列:
#select columns called 'points' and 'blocks'
df_new = df[['points', 'blocks']]
#view new DataFrame
df_new
points blocks
0 25 4
1 12 7
2 15 7
3 14 6
4 19 5
5 23 8
6 25 9
7 29 10
其他资源
下面的教程解释了如何在pandas中执行其他常见操作: