熊猫:.loc [...]的列表式索引

时间:2017-06-11 23:22:31

标签: python pandas indexing

我认为我遗漏了一些非常简单的东西,但我正在尝试使用类似列表的索引与.loc[...]来选择除数据帧中最后一行之外的所有内容。

设定:

import pandas as pd

df = pd.DataFrame({
        'a':[1,2,3,4,5],
        'b':[6,7,8,9,0]
    })

尝试代码:

df.loc[:-1, 'a'] = df.loc[:-1, 'b']

但是df.loc[:-1, 'a']会产生:Series([], Name: a, dtype: int64)而不是那个系列直到最后一行。

期望的结果:

   a  b
0  6  6
1  7  7
2  8  8
3  9  9
4  5  0

工作但是hacky代码:

df.loc[:df.shape[0] - 2, 'a'] = df.loc[:df.shape[0] - 1, 'b']

我的实际代码更复杂并依赖于此代码,所以我不想完全重新发明轮子以获得所需的结果,我想我只是想知道是否有一种简单的方法来查找类似于本机的行python的l[:-1]

2 个答案:

答案 0 :(得分:2)

您尝试将基于标签的索引与整数索引/切片混合使用。您无法使用loc,即基于label- loc 的索引。

Pandas目前提供ix用于混合基于标签和整数的索引。但这将在未来的版本中弃用。

您可以做的一件事是使用索引上的基于整数的切片从索引中获取标签:

In [20]: df.loc[df.index[:-1], 'a']
Out[20]:
0    1
1    2
2    3
3    4
Name: a, dtype: int64

所以你的例子是:

In [22]: df.loc[df.index[:-1], 'a'] = df.loc[df.index[:-1], 'b']

In [23]: df
Out[23]:
   a  b
0  6  6
1  7  7
2  8  8
3  9  9
4  5  0

In [24]:

答案 1 :(得分:1)

使用.iloc进行索引切片:-1。

df.iloc[:-1,df.columns.get_loc('a')] = df.iloc[:-1,df.columns.get_loc('b')]

否则使用.loc,你正在查找标签': - 1'没有返回任何行,因此你将返回[]系列。通过使用df.columns.get_loc,您将返回标记为“a”和“b”的行的列索引。

Output:

   a  b
0  6  6
1  7  7
2  8  8
3  9  9
4  5  0