Pandas .loc与Tuple列名

ezl*_*l33 5 python dataframe pandas

我目前正在与一个使用元组名称的panda合作.当尝试像普通列一样使用.loc时,元组名称会导致它出错.

测试代码如下:

import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randn(6,4),
                   columns=[('a','1'), ('b','2'), ('c','3'), 'nontuple'])
df1.loc[:3, 'nontuple']
df1.loc[:3, ('c','3')]
Run Code Online (Sandbox Code Playgroud)

第二行按预期工作,并从0:3显示"非元组"列.第三行不起作用,而是给出错误:

KeyError:"[[''中没有[('c','3')]在[列]中

知道如何解决这个问题,而不是使用元组作为列名吗?

此外,我发现下面的代码即使.loc没有:

df1.ix[:3][('c','3')]
Run Code Online (Sandbox Code Playgroud)

Max*_*axU 9

Documenation

通过元组访问,返回DF:

In [508]: df1.loc[:3, [('c', '3')]]
Out[508]:
     (c, 3)
0  1.433004
1 -0.731705
2 -1.633657
3  0.565320
Run Code Online (Sandbox Code Playgroud)

通过非元组列访问,返回系列:

In [514]: df1.loc[:3, 'nontuple']
Out[514]:
0    0.783621
1    1.984459
2   -2.211271
3   -0.532457
Name: nontuple, dtype: float64
Run Code Online (Sandbox Code Playgroud)

通过非元组列访问,返回DF:

In [517]: df1.loc[:3, ['nontuple']]
Out[517]:
   nontuple
0  0.783621
1  1.984459
2 -2.211271
3 -0.532457
Run Code Online (Sandbox Code Playgroud)

通过它的号码访问任何列,返回系列:

In [515]: df1.iloc[:3, 2]
Out[515]:
0    1.433004
1   -0.731705
2   -1.633657
Name: (c, 3), dtype: float64
Run Code Online (Sandbox Code Playgroud)

通过它的数字访问任何列,返回DF:

In [516]: df1.iloc[:3, [2]]
Out[516]:
     (c, 3)
0  1.433004
1 -0.731705
2 -1.633657
Run Code Online (Sandbox Code Playgroud)

注意:注意.loc[]和之间的差异.iloc[]- 它们以不同的方式过滤行!

这就像Python的切片一样:

In [531]: df1.iloc[0:2]
Out[531]:
     (a, 1)    (b, 2)    (c, 3)  nontuple
0  0.650961 -1.130000  1.433004  0.783621
1  0.073805  1.907998 -0.731705  1.984459
Run Code Online (Sandbox Code Playgroud)

这包括正确的索引边界:

In [532]: df1.loc[0:2]
Out[532]:
     (a, 1)    (b, 2)    (c, 3)  nontuple
0  0.650961 -1.130000  1.433004  0.783621
1  0.073805  1.907998 -0.731705  1.984459
2 -1.511939  0.167122 -1.633657 -2.211271
Run Code Online (Sandbox Code Playgroud)

  • @CharlieBrummitt,这很有趣!`df1.loc [:3,[('c','3'),'nontuple']]`有效,但``df1.loc [:3,['nontuple',('c','3') ]]`没有.不幸的是,我没有解决方案.一般来说,我会尽量避免使用元组作为列名... (2认同)