将列表列表列表转换为数据帧

时间:2016-08-11 18:46:01

标签: python arrays

我需要帮助将列表列表数组转换为数据帧

我的数据是这样的

[array([[ 0.01568627,  0.01568627,  0.01176471],
   [ 0.01176471,  0.01176471,  0.01176471],
   [ 0.01176471,  0.01176471,  0.01176471],
   ..., 
   [ 0.05098039,  0.05098039,  0.05098039],
   [ 0.04705882,  0.05098039,  0.04705882],
   [ 0.05098039,  0.05098039,  0.04705882]]), array([[ 0.01568627,  0.01568627,  0.01568627],
   [ 0.01176471,  0.01568627,  0.01176471],
   [ 0.01176471,  0.01568627,  0.01568627],
   ..., 
   [ 0.05490196,  0.05098039,  0.05098039],
   [ 0.05098039,  0.05490196,  0.05098039],
   [ 0.05098039,  0.05098039,  0.05098039]])

当我尝试df = pd.DataFrame(lst)时,它无法正常工作

我正在尝试阅读图片并将其放入列表中

我的代码是这样的

for filename in files:
img = misc.imread(filename)
img = img[::2, ::2]
X = (img / 255.0).reshape(-1, 3)
lst.append(X)

当我打印lst

时,我得到了上面的数据

提前致谢!!!

1 个答案:

答案 0 :(得分:0)

考虑从列表理解中与pd.concat()连接。请注意,您将失去两个小数点的精确度以适合float64 dtype。下面将输出一个3列数据帧:

from numpy import array
import pandas as pd

lst = [array([[ 0.01568627,  0.01568627,  0.01176471],
              [ 0.01176471,  0.01176471,  0.01176471],
              [ 0.01176471,  0.01176471,  0.01176471],              
              [ 0.05098039,  0.05098039,  0.05098039],
              [ 0.04705882,  0.05098039,  0.04705882],
              [ 0.05098039,  0.05098039,  0.04705882]]),
       array([[ 0.01568627,  0.01568627,  0.01568627],
              [ 0.01176471,  0.01568627,  0.01176471],
              [ 0.01176471,  0.01568627,  0.01568627],              
              [ 0.05490196,  0.05098039,  0.05098039],
              [ 0.05098039,  0.05490196,  0.05098039],
              [ 0.05098039,  0.05098039,  0.05098039]])]


df = pd.concat([pd.DataFrame(i) for i in lst]).reset_index(drop=True)

print(df)
#            0         1         2
# 0   0.015686  0.015686  0.011765
# 1   0.011765  0.011765  0.011765
# 2   0.011765  0.011765  0.011765
# 3   0.050980  0.050980  0.050980
# 4   0.047059  0.050980  0.047059
# 5   0.050980  0.050980  0.047059
# 6   0.015686  0.015686  0.015686
# 7   0.011765  0.015686  0.011765
# 8   0.011765  0.015686  0.015686
# 9   0.054902  0.050980  0.050980
# 10  0.050980  0.054902  0.050980
# 11  0.050980  0.050980  0.050980