2개의 ARRAY 배열을 인자순서대로 맵핑하여 컬럼과 행으로 이뤄진 TABLE 형식으로 변환하는 방법에 대해 알아 보도록 하겠습니다.
해결방법
각 ARRAY 를 LIST로 변환한 다음
두개의 LIST를 ZIP 함수로 이용해서 DICTIONARY 형태로 변환합니다.
그런 다음에 DICTIONARY를 TABLE 형식인 DATAFRAME으로 변환합니다.
정리하면 각 ARRAY > LIST > LIST ZIP (KEY_LIST, VAL_LIST) > DICTIONARY > DATAFRAME 순서 입니다.
Sample Data
col_array | val_array |
['col1','col2', 'col3', 'col4', 'col5'] | ['val1', 'val2', 'val3', 'val4', 'val5'] |
Result
col1 | col2 | col3 | col4 | col5 |
val1 | val2 | val3 | val4 | val5 |
Code
import pandas as pd
data = {'col_array': [['col1','col2', 'col3', 'col4', 'col5']],
'val_array': [['val1', 'val2', 'val3', 'val4', 'val5']]}
sample_data = pd.DataFrame(data=data)
for index, row in sample_data.iterrows():
col_list = row['col_array'] ## type : <class 'list'>
print(col_list) ## ['col1', 'col2', 'col3', 'col4', 'col5']
val_list = row['val_array'] ## type : <class 'list'>
print(val_list) ## ['val1', 'val2', 'val3', 'val4', 'val5']
df_dict = dict(zip(col_list, val_list)) ## type : <class 'list'> -> <class 'dict'>
print(df_dict) ## {'col1': 'val1', 'col2': 'val2', 'col3': 'val3', 'col4': 'val4', 'col5': 'val5'}
result_data = pd.DataFrame([df_dict]) ## type : <class 'dict'> -> <class 'pandas.core.frame.DataFrame'>
print(type(result_data)) ## <class 'pandas.core.frame.DataFrame'>
print(result_data)
## col1 col2 col3 col4 col5
##0 val1 val2 val3 val4 val5
HOXY ..
다음과 같은 ERROR가 발생했나요?
ValueError: If using all scalar values, you must pass an index
해결방법 알아보기
[Python] ValueError: If using all scalar values, you must pass an index
ValueError: If using all scalar values, you must pass an index 이 에러는 Dictionary 를 Dataframe으로 변경할 때 발생했습니다. df_dict = {'col1': 'val1', 'col2': 'val2', 'col3': 'val3', 'col..
h-a-i.tistory.com
반응형
'IT > Python' 카테고리의 다른 글
[PYTHON] DICTIONARY에서 필요한 KEY 값들 가져오기 (0) | 2020.08.25 |
---|---|
[PYTHON] MySQL에 연결하고 데이터 가져오기 (CONNECT, SELECT) (0) | 2020.08.25 |
[Python] 파일 읽기 - open, read, readline, readlines (0) | 2020.08.24 |
[Python] ValueError: If using all scalar values, you must pass an index (0) | 2020.08.24 |
[Python] Pandas DataFrame의 row 하나씩 출력하기 - iterrows() (0) | 2020.08.24 |