python - 在python中将1*5的列表(对象?)转换为df

标签 python pandas numpy

我有以下结果列表(可以更大):

['2017-09-01.csv', -322.0, -6.5, 99.0, 41, '2017-09-04.csv', -31.0, 3.5, 78.5, 30]

其格式为5*1、5*1等。

我正在寻找以下结果:

Date              A       B    C      D
    '2017-09-01.csv', -322.0, -6.5, 99.0, 41,  
    '2017-09-04.csv', -31.0, 3.5, 78.5, 30

我尝试使用以下代码将其 reshape 为 df:

x_sublists = [results[i:i+5] for i in range(0, len(results), 5)]
df11 = pd.DataFrame(x_sublists [1:], columns=x_sublists [0])

结尾为:

print(df11.shape)
Columns: [(-322.0,), (99.0,), (2017-09-04.csv,), (3.5,), (30,)]
print(df11)
Index: []

我也尝试过这个:

r_reshaped = np.array(results[5:], dtype=object).reshape((0, 5))
df11 = pd.DataFrame(r_reshaped, columns=results[:5])

结尾为:

print(df11.shape)
Columns: [(-322.0,), (99.0,), (2017-09-04.csv,), (3.5,), (30,)]
print(df11)
Index: []

感谢您的建议!

最佳答案

使用 numpy 的 reshape

import numpy as np



l=['2017-09-01.csv', -322.0, -6.5, 99.0, 41, '2017-09-04.csv', -31.0, 3.5, 78.5, 30]

pd.DataFrame(np.array(l).reshape((len(l)//5, 5)),columns=['data','A','B','C','D'])
Out[181]: 
             data       A     B     C   D
0  2017-09-01.csv  -322.0  -6.5  99.0  41
1  2017-09-04.csv   -31.0   3.5  78.5  30

关于python - 在python中将1*5的列表(对象?)转换为df,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222694/

相关文章:

python - 如何将图像存储在 pandas dataframe 列中?

python - 如何在支持多种数据格式的 Pandas 中合并日期?

python - pandas:read_csv仅排除某些行

python - NumPy 更改特定行中符合条件的元素

python - 具有特定格式的 numpy 数组的 Numpy 数组

Python 原生任意精度

python - 如何创建管理系统可以排序的 __unicode__ 字段?

python - wxPython 适合硬件模拟器吗?

python - 来自 python 元组列表的 dask 数据框

python - 将 numpy 数组用于整数和数组输入