반응형
    
    
    
  사전 키가 열 레이블인 다중 인덱스 데이터 프레임에 중첩된 사전
예를 들어 다음과 같은 사전이 있다고 합시다.
dictionary = {'A' : {'a': [1,2,3,4,5],
                     'b': [6,7,8,9,1]},
              'B' : {'a': [2,3,4,5,6],
                     'b': [7,8,9,1,2]}}
그리고 저는 다음과 같은 형태의 데이터 프레임을 원합니다.
     A   B
     a b a b
  0  1 6 2 7
  1  2 7 3 8
  2  3 8 4 9
  3  4 9 5 1
  4  5 1 6 2
이것을 할 수 있는 편리한 방법이 있습니까?시도하는 경우:
In [99]:
DataFrame(dictionary)
Out[99]:
     A               B
a   [1, 2, 3, 4, 5] [2, 3, 4, 5, 6]
b   [6, 7, 8, 9, 1] [7, 8, 9, 1, 2]
저는 각 요소가 목록인 데이터 프레임을 받습니다.위와 같이 각 레벨이 중첩된 dict의 키와 목록의 각 요소에 해당하는 행에 해당하는 다중 인덱스가 필요합니다.아주 조잡한 해결책을 쓸 수 있을 것 같지만 조금 더 간단한 방법이 있었으면 좋겠습니다.
Pandas는 MultiIndex 값을 중첩된 명령이 아닌 튜플로 원합니다.가장 간단한 방법은 사전을 DataFrame에 전달하기 전에 올바른 형식으로 변환하는 것입니다.
>>> reform = {(outerKey, innerKey): values for outerKey, innerDict in dictionary.items() for innerKey, values in innerDict.items()}
>>> reform
{('A', 'a'): [1, 2, 3, 4, 5],
 ('A', 'b'): [6, 7, 8, 9, 1],
 ('B', 'a'): [2, 3, 4, 5, 6],
 ('B', 'b'): [7, 8, 9, 1, 2]}
>>> pandas.DataFrame(reform)
   A     B   
   a  b  a  b
0  1  6  2  7
1  2  7  3  8
2  3  8  4  9
3  4  9  5  1
4  5  1  6  2
[5 rows x 4 columns]
당신은 다음과 같은 기능을 찾고 있습니다..stack:
df = pandas.DataFrame.from_dict(dictionary, orient="index").stack().to_frame()
# to break out the lists into columns
df = pandas.DataFrame(df[0].values.tolist(), index=df.index)
dict_of_df = {k: pd.DataFrame(v) for k,v in dictionary.items()}
df = pd.concat(dict_of_df, axis=1)
python < 3.6의 경우 열 순서가 손실됩니다.
이 재귀적 함수는 다음과 같이 작동해야 합니다.
def reform_dict(dictionary, t=tuple(), reform={}):
    for key, val in dictionary.items():
        t = t + (key,)
        if isinstance(val, dict):
            reform_dict(val, t, reform)
        else:
            reform.update({t: val})
        t = t[:-1]
    return reform
사전의 목록이 동일한 길이가 아닐 경우 BrenBarn의 방법을 적용할 수 있습니다.
>>> dictionary = {'A' : {'a': [1,2,3,4,5],
                         'b': [6,7,8,9,1]},
                 'B' : {'a': [2,3,4,5,6],
                        'b': [7,8,9,1]}}
>>> reform = {(outerKey, innerKey): values for outerKey, innerDict in dictionary.items() for innerKey, values in innerDict.items()}
>>> reform
 {('A', 'a'): [1, 2, 3, 4, 5],
  ('A', 'b'): [6, 7, 8, 9, 1],
  ('B', 'a'): [2, 3, 4, 5, 6],
  ('B', 'b'): [7, 8, 9, 1]}
>>> pandas.DataFrame.from_dict(reform, orient='index').transpose()
>>> df.columns = pd.MultiIndex.from_tuples(df.columns)
   A     B   
   a  b  a  b
0  1  6  2  7
1  2  7  3  8
2  3  8  4  9
3  4  9  5  1
4  5  1  6  NaN
[5 rows x 4 columns]
이 솔루션은 더 큰 데이터 프레임에 적합하며 요구 사항에 적합합니다.
cols = df.columns
int_cols = len(cols)
col_subset_1 = [cols[x] for x in range(1,int(int_cols/2)+1)]
col_subset_2 = [cols[x] for x in range(int(int_cols/2)+1, int_cols)]
col_subset_1_label = list(zip(['A']*len(col_subset_1), col_subset_1))
col_subset_2_label = list(zip(['B']*len(col_subset_2), col_subset_2))
df.columns = pd.MultiIndex.from_tuples([('','myIndex'),*col_subset_1_label,*col_subset_2_label])
산출량
                        A                      B
     myIndex    a              b          c          d
0   0.159710    1.472925    0.619508    -0.476738   0.866238
1   -0.665062   0.609273    -0.089719   0.730012    0.751615
2   0.215350    -0.403239   1.801829    -2.052797   -1.026114
3   -0.609692   1.163072    -1.007984   -0.324902   -1.624007
4   0.791321    -0.060026   -1.328531   -0.498092   0.559837
5   0.247412    -0.841714   0.354314    0.506985    0.425254
6   0.443535    1.037502    -0.433115   0.601754    -1.405284
7   -0.433744   1.514892    1.963495    -2.353169   1.285580
언급URL : https://stackoverflow.com/questions/24988131/nested-dictionary-to-multiindex-dataframe-where-dictionary-keys-are-column-label
반응형
    
    
    
  'programing' 카테고리의 다른 글
| node.js 앱에 대한 코딩 스타일 가이드? (0) | 2023.11.02 | 
|---|---|
| 텍스트를 태그로 래핑 (0) | 2023.11.02 | 
| jQuery 토글 CSS? (0) | 2023.11.02 | 
| MySQL 트리거 행 필드가 존재하는지 확인 (0) | 2023.11.02 | 
| IntelliSense가 SQL Server Management Studio에서 작동하지 않습니다. (0) | 2023.11.02 |