传递列名时数据框为空

时间:2017-02-07 07:04:23

标签: python pandas numpy dataframe

我面临的问题是,在没有列名的情况下将numpy数组传递给dataframe正确初始化它。然而,如果我传递列名,则它是空的。

x = np.array([(1, '1'), (2, '2')], dtype = 'i4,S1')
df = pd.DataFrame(x)
In []: df
Out[]: 
   f0 f1
0   1  1
1   2  2

df2 = pd.DataFrame(x, columns=['a', 'b'])
In []: df2
Out[]: 
Empty DataFrame
Columns: [a, b]
Index: []

2 个答案:

答案 0 :(得分:2)

我认为您需要在参数dtype中指定列名,请参阅DataFrame from structured or record array

x = np.array([(1, '1'), (2, '2')], dtype=[('a', 'i4'),('b', 'S1')])
df2 = pd.DataFrame(x)
print (df2)
   a     b
0  1  b'1'
1  2  b'2'

没有参数dtype的另一种解决方案:

x = np.array([(1, '1'), (2, '2')])
df2 = pd.DataFrame(x, columns=['a', 'b'])
print (df2)
   a  b
0  1  1
1  2  2

答案 1 :(得分:0)

它是dtype param,没有指定它,它按预期工作。 请参阅文档DataFrame

中的示例
import numpy as np
import pandas as pd

x = np.array([(1, "11"), (2, "22")])
df = pd.DataFrame(x)
print df

df2 = pd.DataFrame(x, columns=['a', 'b'])
print df2