我看到 python DataFrames 有时使用 [index,:] 符号进行子集化,而有时使用 [index] 就足够了。
使用一个简单的玩具示例:
df = pd.DataFrame({'a':[1,5,10,15,20,50,88]})
idx = [2,4,6]
我们可以使用以下任一方法调用 iloc 方法:
df.iloc[idx,:]
df.iloc[idx]
获取结果:
a
2 10
4 20
6 88
调用方式有区别吗?我应该更喜欢使用其中一种吗?
最佳答案
在 df.iloc[idx,:]
中,冒号分割列。在 python 中,当你使用 [:] 时,你会切掉所有选项。例如:
df = pd.DataFrame({'a':[1,5,10,15,20,50,88], 'b':[1,5,10,15,20,50,88]})
idx = [2,4,6]
没有列切片:
df.iloc[idx]
输出:
a b
2 10 10
4 20 20
6 88 88
使用列切片:
df.iloc[idx,:1]
输出:
a
2 10
4 20
6 88
在这种情况下,问题是您是否要显式切分所有列。以我谦虚的观点,我认为标准形式 df.iloc[idx]
会很清楚。
http://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-position
关于Python子集和切片 [index, :] format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36024475/