본문 바로가기
Development/Python

[Python] Dataframe 2개의 컬럼을 활용하여 Dictionary 생성

by 성딱이 2022. 1. 4.
반응형

1. 예제 DataFrame

df = pd.DataFrame({'col_A':['a','b','c','d']
                   ,'col_B':[0,1,2,3]})

 

2. 방법

# dict(zip(df.col_A, df.col_B))

target_dict = dict(zip(df.col_A, df.col_B))

 

3. 다른 방법과 속도 비교

In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB'))


In [7]: %timeit dict(zip(df.A, df.B))
10.9 ms ± 330 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict()
10.8 ms ± 658 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [9]: %timeimt df.set_index('A').to_dict()['B']
10.7 ms ± 359 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

 

출처 : https://stackoverflow.com/questions/17426292/how-to-create-a-dictionary-of-two-pandas-dataframe-columns

 

How to create a dictionary of two pandas DataFrame columns

What is the most efficient way to organise the following pandas Dataframe: data = Position Letter 1 a 2 b 3 c 4 d 5 e into a dictionary like

stackoverflow.com

 

 

반응형

댓글