这篇文章仅适用于所有列具有相同数据类型的数据框。
如果要选择的列使用 内的切片彼此保持规则的步幅,则这是可能的.iloc。因此,选择任意两列始终是可能的,但对于两列以上,我们需要在它们之间有规则的步幅。在所有这些情况下,我们需要知道它们的列 ID 和步幅。
让我们尝试借助一些示例案例来理解这些内容。
情况 #1:从第 0 列 ID 开始的两列
In [47]: df1
Out[47]:
a b c d
0 5 0 3 3
1 7 3 5 2
2 4 7 6 8
In [48]: np.array_equal(df1.loc[:, ['a', 'b']], df1.iloc[:,0:2])
Out[48]: True
In [50]: np.shares_memory(df1, df1.iloc[:,0:2]) # confirm view
Out[50]: True
Run Code Online (Sandbox Code Playgroud)
情况#2:从第 1 列 ID 开始的两列
In [51]: df2
Out[51]:
a0 a a1 a2 b c d
0 8 1 6 7 7 8 1
1 5 8 4 3 0 3 5
2 0 2 3 8 1 3 3
In [52]: np.array_equal(df2.loc[:, ['a', 'b']], df2.iloc[:,1::3])
Out[52]: True
In [54]: np.shares_memory(df2, df2.iloc[:,1::3]) # confirm view
Out[54]: True
Run Code Online (Sandbox Code Playgroud)
情况#2:从第一个列 ID 开始的三列,跨度为 2 列
In [74]: df3
Out[74]:
a0 a a1 b b1 c c1 d d1
0 3 7 0 1 0 4 7 3 2
1 7 2 0 0 4 5 5 6 8
2 4 1 4 8 1 1 7 3 6
In [75]: np.array_equal(df3.loc[:, ['a', 'b', 'c']], df3.iloc[:,1:6:2])
Out[75]: True
In [76]: np.shares_memory(df3, df3.iloc[:,1:6:2]) # confirm view
Out[76]: True
Run Code Online (Sandbox Code Playgroud)
选择 4 列:
In [77]: np.array_equal(df3.loc[:, ['a', 'b', 'c', 'd']], df3.iloc[:,1:8:2])
Out[77]: True
In [78]: np.shares_memory(df3, df3.iloc[:,1:8:2])
Out[78]: True
Run Code Online (Sandbox Code Playgroud)