从数组的字典中创建一个数据框:
In [571]: df = pd.DataFrame({'a':['one','two','three'], 'b':np.arange(3), 'c':np.ones(3)})
In [572]: df
Out[572]:
a b c
0 one 0 1.0
1 two 1 1.0
2 three 2 1.0
注意混合列数据类型:
In [579]: df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 a 3 non-null object
1 b 3 non-null int64
2 c 3 non-null float64
dtypes: float64(1), int64(1), object(1)
memory usage: 200.0+ bytes
如果我们从中请求一个 numpy,我们会得到一个 2d 对象 dtype 数组:
In [580]: df.values
Out[580]:
array([['one', 0, 1.0],
['two', 1, 1.0],
['three', 2, 1.0]], dtype=object)
重新创建一个数据框,看起来一样,但列 dtypes 不同:
In [581]: pd.DataFrame(df.values, columns=['a','b','c'])
Out[581]:
a b c
0 one 0 1.0
1 two 1 1.0
2 three 2 1.0
In [582]: _.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 a 3 non-null object
1 b 3 non-null object
2 c 3 non-null object
dtypes: object(3)
memory usage: 200.0+ bytes
但结构化数组确实保留了列 dtpes:
In [587]: df.to_records(index=False)
Out[587]:
rec.array([('one', 0, 1.), ('two', 1, 1.), ('three', 2, 1.)],
dtype=[('a', 'O'), ('b', '<i8'), ('c', '<f8')])
In [588]: pd.DataFrame(_)
Out[588]:
a b c
0 one 0 1.0
1 two 1 1.0
2 three 2 1.0
In [589]: _.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 a 3 non-null object
1 b 3 non-null int64
2 c 3 non-null float64
dtypes: float64(1), int64(1), object(1)
memory usage: 200.0+ bytes