gpt4 book ai didi

python - 在 Pandas 中将列表转换并 reshape 为 DataFrame

转载 作者:行者123 更新时间:2023-12-04 18:06:56 35 4
gpt4 key购买 nike

如何将 list(x) 转换为 10x3 数据框?我想使用列表中的前 3 个条目作为列名。接下来的三个条目进入第 1 行,之后的三个进入第 2 行,依此类推。换句话说,我的数据框将是 3 列,其中包含这三个名称“Phase”、“Formula”、“Sat Indx”。那么第 1 行的条目将是方解石、CaCO3、.8409。

我尝试了以下操作,但出现错误:

z=DataFrame(x, columns=['Phase','Formula','Sat Indx'])

print(x)

[u'Phase ',
u'Formula ',
u'Sat Indx',
u'Calcite ',
u'CaCO3 ',
0.8409314786906652,
u'Aragonite ',
u'CaCO3 ',
0.6971616312984299,
u'H2O(g) ',
u'H2O ',
-1.5101143330253721,
u'CO2(g) ',
u'CO2 ',
-1.5522870578743806,
u'Gypsum ',
u'CaSO4:2H2O ',
-2.993649142404755,
u'Anhydrite ',
u'CaSO4 ',
-3.2135284668446644,
u'Portlandite ',
u'Ca(OH)2 ',
-10.738067251525967,
u'H2(g) ',
u'H2 ',
-22.6,
u'O2(g) ',
u'O2 ',
-37.98786977495807,
u'CH4(g) ',
u'CH4 ',
-66.16971681191183]

最佳答案

您应该首先将列表转换为更合适的格式。

一个选项是将其转换为具有列表理解的子列表列表(每行一个子列表):

In [10]: x_sublists = [x[i:i+3] for i in range(0, len(x), 3)]

In [11]: pd.DataFrame(x_sublists [1:], columns=x_sublists [0])
Out[11]:
Phase Formula Sat Indx
0 Calcite CaCO3 0.840931478691
1 Aragonite CaCO3 0.697161631298
2 H2O(g) H2O -1.51011433303
3 CO2(g) CO2 -1.55228705787
4 Gypsum CaSO4:2H2O -2.9936491424
5 Anhydrite CaSO4 -3.21352846684
6 Portlandite Ca(OH)2 -10.7380672515
7 H2(g) H2 -22.6
8 O2(g) O2 -37.987869775
9 CH4(g) CH4 -66.1697168119

另一种选择是将列表 reshape 为一个 numpy 数组(但这有一个缺点,即导致一个带有对象 dtype 的列,如@DSM 所述,因此要得到与上面相同的结果,该列应设置为手动 float ):

In [67]: x_reshaped = np.array(x[3:], dtype=object).reshape((-1, 3))

In [68]: df = pd.DataFrame(x_reshaped, columns=x[:3])

In [69]: df['Sat Indx'] = df['Sat Indx'].astype(float)

关于python - 在 Pandas 中将列表转换并 reshape 为 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24108842/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com