2024-06-13 05:40:15 发布
网友
我试图得到这些表的总值
building_weight_and_height = {'Floor': ['Roof','10th','9th','8th','7th','6th','5th','4th','3rd','2nd'], 'DL(kN)': [1200,1200,1200,1200,1200,1200,1200,1200,1200,1200], 'StoreyHeight': [3,3,3,3,3,3,3,3,3,4]}
预期产量:
Output image
一个快速的方法,我相信还有其他方法:
import pandas as pd dics = {'Floor': ['Roof','10th','9th','8th','7th','6th','5th','4th','3rd','2nd'], 'DL(kN)': [1200,1200,1200,1200,1200,1200,1200,1200,1200,1200], 'StoreyHeight': [3,3,3,3,3,3,3,3,3,4]} df = pd.DataFrame(columns=['Floor','DL(kN)','StoreyHeight']) print (df) df['Floor'] = dics['Floor'] df['DL(kN)'] = dics['DL(kN)'] df['StoreyHeight'] = dics['StoreyHeight'] totalDL = df['DL(kN)'].sum() totalSH = df['StoreyHeight'].sum() df=df.append({'Floor':'Total','DL(kN)':totalDL,'StoreyHeight':totalSH},ignore_index=True) print (df)
输出如下:
Floor DL(kN) StoreyHeight 0 Roof 1200 3 1 10th 1200 3 2 9th 1200 3 3 8th 1200 3 4 7th 1200 3 5 6th 1200 3 6 5th 1200 3 7 4th 1200 3 8 3rd 1200 3 9 2nd 1200 4 10 Total 12000 31
从字典创建数据帧,并使用pd.DataFrame.loc添加行:
pd.DataFrame.loc
import pandas as pd building_weight_and_height = {'Floor': ['Roof','10th','9th','8th','7th','6th','5th','4th','3rd','2nd'], 'DL(kN)': [1200,1200,1200,1200,1200,1200,1200,1200,1200,1200], 'StoreyHeight': [3,3,3,3,3,3,3,3,3,4]} df = pd.DataFrame(building_weight_and_height) df = df[['Floor', 'DL(kN)', 'StoreyHeight']] # alternatively: # df = pd.DataFrame(building_weight_and_height, columns=['Floor', 'DL(kN)', 'StoreyHeight']) df.loc[len(df.index)+1] = ['Total', df['DL(kN)'].sum(), df['StoreyHeight'].sum()] print(df) # Floor DL(kN) StoreyHeight # 0 Roof 1200 3 # 1 10th 1200 3 # 2 9th 1200 3 # 3 8th 1200 3 # 4 7th 1200 3 # 5 6th 1200 3 # 6 5th 1200 3 # 7 4th 1200 3 # 8 3rd 1200 3 # 9 2nd 1200 4 # 11 Total 12000 31
你有什么问题
>>> sum(building_weight_and_height['DL(kN)']) 12000 >>> sum(building_weight_and_height['StoreyHeight']) 31
一个快速的方法,我相信还有其他方法:
输出如下:
从字典创建数据帧,并使用
pd.DataFrame.loc
添加行:你有什么问题
相关问题 更多 >
编程相关推荐