我有以下结果
列表(可以更大):
['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/