为什么在Python中df[[2,3,4]][2:4]有效而df[[2:4]][2:4]无效

为什么在Python中df[[2,3,4]][2:4]有效而df[[2:4]][2:4]无效,python,pandas,dataframe,subset,Python,Pandas,Dataframe,Subset,假设我们有一个数据帧 import pandas as pd df = pd.read_csv('...') df 0 1 2 3 4 0 1 2 3 4 5 1 1 2 3 4 5 2 1 2 3 4 5 3 1 2 3 4 5 4 1 2 3 4 5 为什么一种方法有效而另一种方法返回语法错误?我认为您需要: 它失败是因为2:4是访问df的键/列的无效语法: In [73]: df[[2:4]] File "<ipython-input-73-f0f09617b349>

假设我们有一个数据帧

import pandas as pd
df = pd.read_csv('...')
df
  0 1 2 3 4
0 1 2 3 4 5
1 1 2 3 4 5
2 1 2 3 4 5
3 1 2 3 4 5
4 1 2 3 4 5
为什么一种方法有效而另一种方法返回语法错误?

我认为您需要:


它失败是因为
2:4
是访问df的键/列的无效语法:

In [73]:
df[[2:4]]
  File "<ipython-input-73-f0f09617b349>", line 1
    df[[2:4]]
         ^
SyntaxError: invalid syntax
然后通过切片选择行:

In [79]:
df[[2,3,4]][2:4]

Out[79]:
   2  3  4
2  3  4  5
3  3  4  5

对不起,我的可乐来了。现在我看到了第二个答案,我认为这是一个很好的解释。我认为最好是用于选择函数,如,或。
In [74]:
d = {0:0,1:1,2:2,3:3,4:4,5:5}
d

Out[74]:
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5}

In [76]:
d[[2:4]]

  File "<ipython-input-76-ea5d68adc389>", line 1
    d[[2:4]]
        ^
SyntaxError: invalid syntax
In [77]:
df[[2,3,4]]

Out[77]:
   2  3  4
0  3  4  5
1  3  4  5
2  3  4  5
3  3  4  5
4  3  4  5
In [79]:
df[[2,3,4]][2:4]

Out[79]:
   2  3  4
2  3  4  5
3  3  4  5