2014-10-06 5 views
-1

필자는 무작위로 걷는 쌍 단위 상호 작용 (행 단위)의 대형 판다 데이터 프레임이있는 프로그램을 가지고 있습니다. 각각의 연속적인 단계에 대한 옵션의 목록은 팬더 멀티 인덱스 : 내가 뭘 잘못하고 있니?

df_options = df[(df.A == x) & (df.B == y)] 

내가 위의 같은 구문을 사용하여 작업하는 일을했다, 그래서 기본적으로 두 개의 열에서 특정 값을 기준으로 전체 dataframe에서 좁혀하지만이 될 것처럼 보였다된다 그래서 같은 인덱스 A를 DF, B에 속도 측면에서 좋은 생각 (어떤이 제한되었다) : 그 내가 무작위로 기록 된 방법 때문에

df.sort(['A', 'B'], inplace=True) 
df.index = df.index.rename('idx') 
df = df.set_index(['A', 'B'], drop=False, append=True, verify_integrity=True) 

(나는 'IDX'로 원래의 인덱스를 유지하고있어주의 걷고 특정 행에 액세스)
그런 다음 원래 df_options 코드를 먼저I가 특정 값을 필요 df.xs((x, y), level=('A', 'B'))
그와 갖는 문제 후 53,210, 또한
df.loc(axis=0)[:,A,B]

가 원래 구

df_options.xs(new, level='idx')['sim'].values[0] 

또는

df_options.loc[new, 'sim'] 

변경

df_options.loc(axis=0)[new,:,:]['sim'].values[0] 

("새로운"무작위로 선택한 다음 안양의 인덱스 및 '시뮬레이션은'페어 유사성 점수의 열입니다.) 나는이 작업을 얻으려고 멀리 해킹으로

, 나는이 같은 오류를 얻고 유지 '...not hashable'AttributeError: 'Int64Index' object has no attribute 'get_loc_level

다음 호 제목의 질문에 대한 답입니다. 무엇이 잘못 되었나요? 더 구체적으로 말하자면,
1) multiindex는 정말로 내가 생각하는 것처럼이 프로세스를 가속화 할 잠재력이 있습니까?
2) 그렇다면 여기에 사용할 올바른 숙어는 무엇입니까 (느낌이 비슷합니다 .xs. and .loc),
3) 아니면 원시 numpy 같은 다른 사용해야합니까?

EDIT 코드로 예제를 만드는 과정에서 나는 그 코드를 작동시킬 수있었습니다. 나는 .values[0] (row.p2.values[0]df.index[rand_pair][0][0])과 같은 어색한 농구를 뛰어 넘어야한다고 말합니다. 제프에 대응

: 팬더 0.14.1

df.info() 
<class 'pandas.core.frame.DataFrame'> 
MultiIndex: 561567 entries, (0, 0, 003) to (561566, 26127, 011) 
Data columns (total 14 columns): 
p1    561567 non-null int64 
smp1   561567 non-null object 
rt1    561567 non-null float64 
cas1   561567 non-null object 
sim1   561567 non-null float64 
p2    561567 non-null int64 
smp2   561567 non-null object 
rt2    561567 non-null float64 
cas2   561567 non-null object 
sim2   561567 non-null float64 
nlsim1   561567 non-null float64 
sum_spec_sq1 561567 non-null float64 
sum_spec_sq2 561567 non-null float64 
sum_s1s2  561567 non-null float64 
dtypes: float64(8), int64(2), object(4) 

참고 : "P1", "smp2"및 "nlsim1는"의 "A" "B"및 "심"에 해당 내 위의 질문.몇 단계를 걸어 충분한 데이터 :

samples = set([c for a, b, c in df.index.values]) 
df_numbered = range(df.shape[0]) 
#rand_pair = random.sample(df_numbered, 1) 
rand_pair = [0] 
path = [df.index[rand_pair][0][0]] 

걸어서 (그것을 반복) :

row = df.loc[path[-1],:,:] 
p = row.p2.values[0] 
smp = row.smp2.values[0] 
print p, smp 
samples.discard(smp) 
print sorted(list(samples)) 
pick_sample = random.sample(samples, 1)[0] 
print pick_sample 
df_options = df.xs((p, pick_sample), level=('p1', 'smp2')) 
if df_options.shape[0] < 1: 
    print "out of options, stop iterating" 
    print "path=", path 
else: 
    print "# options: ", df_options.shape[0] 
    new = weighted_random_choice() 
    path.append(new) 
    print path 
    print "you should keep going" 

출력, 1 단계 :

13307 010 
[u'002', u'016'] 
016 
# options: 1 
[174513, 270870] 
you should keep going 

df = pd.DataFrame({u'nlsim1': {174513: 0.8782, 270870: 0.9461, 478503: 0.8809}, 
u'p1': {174513: 8655, 270870: 13307, 478503: 22276}, 
u'p2': {174513: 13307, 270870: 22276, 478503: 2391}, 
u'smp1': {174513: u'007', 270870: u'010', 478503: u'016'}, 
u'smp2': {174513: u'010', 270870: u'016', 478503: u'002'}}) 
df.index = df.index.rename('idx') 
df = df.set_index(['p1', 'smp2'], drop=False, append=True, verify_integrity=True) 

def weighted_random_choice(): 
    options = df_options.index.tolist() 
    tot = df_options.nlsim1.sum() 
    options_weight = df_options.nlsim1/tot 
    return np.random.choice(options, p=list(options_weight)) 

는 산책을 시작합니다

두 번째 단계 :

22276 016 
[u'002'] 
002 
# options: 1 
[174513, 270870, 478503] 
you should keep going 

예상대로 3 단계 오류가 발생하여 샘플이 부족합니다. 은 "선택 특정 A, B를 변화시킴으로써

dfi = df.set_index(['A', 'B']) 

:

+3

글쎄, 입출력에 대한 완전한 복사/붙여 넣기 예제, 실제 데이터 세트에 대한 df.info() 및 팬더 버전을 보여줘야합니다. – Jeff

+0

@Jeff 나는 당신을 위해 붙여 넣을 수있는 코드 작업을하고 있습니다. 내 생각 엔 내가 완전히, 분명히 잘못하고있는 것이었지만 세부 사항에 대한 귀하의 요청은 저에게 희망을주었습니다 ... –

+0

이제 입력 프레임 샘플과 기대하는 출력이 필요합니다 (복사/붙여 넣기 및 runable, 무작위 데이터 만 생성하면됩니다.하지만 색인은 현재하고있는 것과 일치해야합니다.) df.info()는 실제 데이터에 대한 아이디어를 제공합니다. – Jeff

답변

0

음, 간단한 수정은 데이터 프레임, 일본어 및 'A'및 'B'에 의해 인덱스 다른 하나의 두 복사본을 사용하는 것이었다 "

df_options = dfi.loc(axis=0)[x, y] 

df_options = df[(df.A == x) & (df.B == y)] 

에서 패러다임은 나는 속도가 5 배 향상을 얻을 수 있었다. df의 크기에 따라 확장이 잘되어야합니다.

관련 문제