[python] 항목의 길이가 다른 사전에서 데이터 프레임 만들기

10 개의 키-값 쌍이있는 사전이 있다고 가정 해 보겠습니다. 각 항목에는 numpy 배열이 있습니다. 그러나 배열의 길이는 모두 동일하지 않습니다.

각 열에 다른 항목이있는 데이터 프레임을 만들려면 어떻게해야합니까?

내가 시도 할 때 :

pd.DataFrame(my_dict)

나는 얻다:

ValueError: arrays must all be the same length

이것을 극복 할 방법이 있습니까? Pandas NaN가 더 짧은 항목을 위해 해당 열을 채우는 데 사용하게 되어 기쁩니다 .



답변

Python 3.x에서 :

In [6]: d = dict( A = np.array([1,2]), B = np.array([1,2,3,4]) )

In [7]: pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in d.items() ]))
Out[7]:
    A  B
0   1  1
1   2  2
2 NaN  3
3 NaN  4

Python 2.x에서 :

교체 d.items()와 함께 d.iteritems().


답변

이를 수행하는 간단한 방법은 다음과 같습니다.

In[20]: my_dict = dict( A = np.array([1,2]), B = np.array([1,2,3,4]) )
In[21]: df = pd.DataFrame.from_dict(my_dict, orient='index')
In[22]: df
Out[22]:
   0  1   2   3
A  1  2 NaN NaN
B  1  2   3   4
In[23]: df.transpose()
Out[23]:
    A  B
0   1  1
1   2  2
2 NaN  3
3 NaN  4


답변

구문을 정리하는 방법은 기본적으로 다른 답변과 동일한 작업을 수행합니다.

>>> mydict = {'one': [1,2,3], 2: [4,5,6,7], 3: 8}

>>> dict_df = pd.DataFrame({ key:pd.Series(value) for key, value in mydict.items() })

>>> dict_df

   one  2    3
0  1.0  4  8.0
1  2.0  5  NaN
2  3.0  6  NaN
3  NaN  7  NaN

목록에도 비슷한 구문이 있습니다.

>>> mylist = [ [1,2,3], [4,5], 6 ]

>>> list_df = pd.DataFrame([ pd.Series(value) for value in mylist ])

>>> list_df

     0    1    2
0  1.0  2.0  3.0
1  4.0  5.0  NaN
2  6.0  NaN  NaN

목록의 또 다른 구문은 다음과 같습니다.

>>> mylist = [ [1,2,3], [4,5], 6 ]

>>> list_df = pd.DataFrame({ i:pd.Series(value) for i, value in enumerate(mylist) })

>>> list_df

   0    1    2
0  1  4.0  6.0
1  2  5.0  NaN
2  3  NaN  NaN

추가로 결과를 전치하거나 열 데이터 유형 (float, integer 등)을 변경해야 할 수도 있습니다.


답변

이것은 OP의 질문에 직접 대답하지는 않지만. 나는 불평등 한 배열이 있고 공유하고 싶을 때 이것이 내 경우에 훌륭한 솔루션이라는 것을 알았습니다.

pandas 문서에서

In [31]: d = {'one' : Series([1., 2., 3.], index=['a', 'b', 'c']),
   ....:      'two' : Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
   ....:

In [32]: df = DataFrame(d)

In [33]: df
Out[33]:
   one  two
a    1    1
b    2    2
c    3    3
d  NaN    4


답변

객체 목록 pd.concataxis=1함께 사용할 수도 있습니다 pd.Series.

import pandas as pd, numpy as np

d = {'A': np.array([1,2]), 'B': np.array([1,2,3,4])}

res = pd.concat([pd.Series(v, name=k) for k, v in d.items()], axis=1)

print(res)

     A  B
0  1.0  1
1  2.0  2
2  NaN  3
3  NaN  4


답변

다음 두 줄 모두 완벽하게 작동합니다.

pd.DataFrame.from_dict(df, orient='index').transpose() #A

pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in df.items() ])) #B (Better)

그러나 Jupyter의 % timeit을 사용하면 B와 A의 속도가 4 배로 증가합니다. 이는 특히 대규모 데이터 세트 (주로 많은 수의 열 / 기능 포함)로 작업 할 때 매우 인상적입니다.


답변

표시하지 않으려 고 NaN두 개의 특정 길이가있는 경우 나머지 각 셀에 ‘공백’을 추가하는 것도 작동합니다.

import pandas

long = [6, 4, 7, 3]
short = [5, 6]

for n in range(len(long) - len(short)):
    short.append(' ')

df = pd.DataFrame({'A':long, 'B':short}]
# Make sure Excel file exists in the working directory
datatoexcel = pd.ExcelWriter('example1.xlsx',engine = 'xlsxwriter')
df.to_excel(datatoexcel,sheet_name = 'Sheet1')
datatoexcel.save()

   A  B
0  6  5
1  4  6
2  7
3  3   

길이가 2 개 이상인 경우 유사한 방법을 사용하는 함수를 만드는 것이 좋습니다.