[英]Convert Series to Dataframe in Python
我們需要在 Python 3 中將三個不同的系列轉換為一個dataframe
。
系列 1(平均值):
e1 40.355
e2 59.556
ec1 17.668
ec2 75.230
系列 2 (SD):
e1 19.815
e2 17.550
ec1 14.704
ec2 54.485
系列 3(最大):
e1 87.36
e2 80.39
ec1 200.3
ec2 207.5
以上需要合並成一個如下所示的數據框:
Features Mean Standard Deviation Max
e1 40.355 19.815 87.36
e2 59.556 17.550 80.39
ec1 17.668 14.704 200.3
ec2 75.230 54.485 207.5
到目前為止我們所做的是:
if __name__ == '__main__':
Mean = df.mean().round(3)
SD = df.std().round(3)
Max = df.max()
df2 = pd.DataFrame(columns=['Features', 'Mean', 'Standard Deviation', 'Max'])
df2['Mean'] = Mean
df2['Standard Deviation'] = SD
df2['Max'] = Max
print(df2)
以上打印/輸出以下內容:
Features Mean Standard Deviation Max
e1 NaN 40.355 19.815 87.36
e2 NaN 59.556 17.550 80.39
ec1 NaN 17.668 14.704 200.3
ec2 NaN 75.230 54.485 207.5
我們如何將索引設置為 features 列,以便數據框如下所示:
Features Mean Standard Deviation Max
e1 40.355 19.815 87.36
e2 59.556 17.550 80.39
ec1 17.668 14.704 200.3
ec2 75.230 54.485 207.5
使用concat
、 rename_axis
和reset_index
:
df2 = (pd.concat([Mean, SD, Max],
keys=["Mean", "SD", "Max"],
axis=1)
.rename_axis(index="Features")
.reset_index())
>>> df2
Features Mean SD Max
0 e1 40.355 19.815 87.36
1 e2 59.556 17.550 80.39
2 ec1 17.668 14.704 200.30
3 ec2 75.230 54.485 207.50
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.