J'essaie d'obtenir les valeurs totales de ces tableaux
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]}
Production attendue:
3 réponses
Un moyen rapide, je suis sûr qu'il peut y avoir d'autres moyens:
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)
Sortie comme ci-dessous:
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
Quels sont tes problèmes?
>>> sum(building_weight_and_height['DL(kN)'])
12000
>>> sum(building_weight_and_height['StoreyHeight'])
31
Créez une trame de données à partir du dictionnaire et ajoutez une ligne à l'aide de 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
Questions connexes
De nouvelles questions
python
Python est un langage de programmation multi-paradigme, typé dynamiquement et polyvalent. Il est conçu pour être rapide à apprendre, comprendre, utiliser et appliquer une syntaxe propre et uniforme. Veuillez noter que Python 2 est officiellement hors support à partir du 01-01-2020. Néanmoins, pour les questions Python spécifiques à la version, ajoutez la balise [python-2.7] ou [python-3.x]. Lorsque vous utilisez une variante Python (par exemple, Jython, PyPy) ou une bibliothèque (par exemple, Pandas et NumPy), veuillez l'inclure dans les balises.