获取列(pandas)中唯一值的索引

时间:2015-06-25 11:30:14

标签: python pandas

我需要在x中获取具有唯一值的行号。我来到以下解决方案:

x = pv.index.get_level_values("Код") #get index level values
dups = x[x.duplicated()].unique() #get dup. values
uniques = x[~x.isin(dups)] #get not dup. values
uniques_indexes = np.where(x.isin(uniques))[0].tolist()

我认为计算太多了。有没有更好的解决方案?

1 个答案:

答案 0 :(得分:2)

import pandas as pd
import numpy as np

np.random.seed(100)
index = np.random.choice('A B C D E F G'.split(), 10)
pv = pd.DataFrame(np.random.randn(10), index=index, columns=['value'])

Out[60]: 
    value
A -0.2347
A -1.4397
D  0.4328
A  2.3045
C -0.1226
G  0.0155
E  0.2660
C -0.1138
F  1.0111
C -1.4408

# reset_index first to preserve the line number
pv.reset_index(inplace=True)

Out[128]: 
  index   value
0     A -0.2347
1     A -1.4397
2     D  0.4328
3     A  2.3045
4     C -0.1226
5     G  0.0155
6     E  0.2660
7     C -0.1138
8     F  1.0111
9     C -1.4408

# replace your groupby index level
pv.sort_index().groupby('index').filter(lambda group: len(group) == 1)


Out[129]: 
  index   value
2     D  0.4328
5     G  0.0155
6     E  0.2660
8     F  1.0111