Possible data inputs to DataFrame constructor

Possible data inputs to DataFrame constructor:

import pandas as pd
import numpy as np

(1) 2D ndarray

pd.DataFrame(np.arange(12).reshape(3,4))
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11

(2)dict of arrays,lists,tuples or series

pd.DataFrame({'a':[1,2,3],'b':[2,3,4],'c':[4,5,6]})
a b c
0 1 2 4
1 2 3 5
2 3 4 6
pd.DataFrame({'a':np.array([1,2,3]),'b':np.array([2,3,4]),'c':np.arange(3)})
a b c
0 1 2 0
1 2 3 1
2 3 4 2
a=pd.Series([1,2,3]);b=pd.Series([2,3,4]);c=pd.Series([0,1,2])
pd.DataFrame({'a':a,'b':b,'c':c})
a b c
0 1 2 0
1 2 3 1
2 3 4 2

(3)dict of dicts

pd.DataFrame({'a':{0:1,1:2,2:3},'b':{0:2,1:3,2:3},'c':{0:0,1:1,2:2}})
a b c
0 1 2 0
1 2 3 1
2 3 3 2

(4)list of lists or tuples

a=pd.DataFrame([[1,2,3],[2,3,4],[0,1,2]],index=['aa','bb','cc'],columns=['a','b','c']);a
a b c
aa 1 2 3
bb 2 3 4
cc 0 1 2

(5)another DataFrame's values

pd.DataFrame(a.values,index=['naa','nbb','ncc'],columns=['na','nb','nc']) #Note that,using a.values
na nb nc
naa 1 2 3
nbb 2 3 4
ncc 0 1 2

猜你喜欢

转载自www.cnblogs.com/johnyang/p/12611416.html