답변:
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().
pd.Series(...) (가정 import pandas as pd가져 오기 섹션에서)
pd.DataFrame({k: pd.Series(l) for k, l in d.items()})
이를 수행하는 간단한 방법은 다음과 같습니다.
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의 질문에 직접 대답하지는 않지만. 나는 불평등 한 배열이 있고 공유하고 싶을 때 이것이 내 경우에 훌륭한 솔루션이라는 것을 알았습니다.
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
표시하지 않으려 고 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 개 이상인 경우 유사한 방법을 사용하는 함수를 만드는 것이 좋습니다.