如何让数据框解释construtor中的类型?截至目前,它将所有内容保持为“对象”
这是我现在的代码:
arr = list(range(120)) + [21]*100
cat = ["A"]*20 + ["B"]*40 + ["C", "D"] * 20 + ["E", "F" ,"G"] * 30
df = pd.DataFrame([arr]*3 + [cat], index = ["a1", "a2", "a3", "cat"]).T
print(df.a1.dtype.name)
print(df.a3.dtype.name)
print(df.cat.dtype.name)
object
object
object
答案 0 :(得分:1)
试试这个:
np_array = np.array([arr]*3 + [cat])
dict = {"a1":np_array[0], "a2":np_array[1], "a3":np_array[2]}
df = pd.concat([pd.DataFrame({"cat":np_array[3]}), pd.DataFrame(dict, dtype = 'int64')], names = ["a1", "a2", "a3", "cat"], axis = 1)