从形状(m,n)的numpy数组创建Pandas系列

时间:2019-05-23 09:12:41

标签: python python-3.x pandas numpy

我正在努力使object SensorDataService { var sensorData: SensorData? = null } data class SensorData(val name: String, val temp : Double) 构造函数了解我希望每个单元格包含一个列表。它适用于形状Series,但不适用于形状(m,)

(m, n)

是否有将import pandas as pd import numpy as np print(pd.__version__) # 0.24.1 index = ['a', 'b', 'c'] ### 1 - shape (m,) is OK ### data1 = np.array([[1, 2, 3], [4, 5], [6, 7, 8, 9]]) print(data1.shape) # (3,) series1 = pd.Series(index=index, data=data1) print(series1) # a [1, 2, 3] # b [4, 5] # c [6, 7, 8, 9] # dtype: object ### 2 - shape (m,n) is NOT OK ### data2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(data2.shape) # (3, 3) series2 = pd.Series(index=index, data=data2) # Traceback (most recent call last): # File "test.py", line 25, in <module> # series2 = pd.Series(index=index, data=data2) # File "/home/dev/virtualenv/py-cnn/lib64/python3.6/site-packages/pandas/core/series.py", line 262, in __init__ # raise_cast_failure=True) # File "/home/dev/virtualenv/py-cnn/lib64/python3.6/site-packages/pandas/core/internals/construction.py", line 658, in sanitize_array # raise Exception('Data must be 1-dimensional') # Exception: Data must be 1-dimensional 数组形状转换为numpy或了解(m,) Serie构造函数的想法?

1 个答案:

答案 0 :(得分:1)

使用tolist

series2 = pd.Series(index=index, data=data2.tolist())

print(series2)
a    [1, 2, 3]
b    [4, 5, 6]
c    [7, 8, 9]
dtype: object