I want to add or multiply the same key values in the dictionary file

Asked 2 years ago, Updated 2 years ago, 70 views

P1 {'amphibolite.txt': 0.00593448307396262, 'basalt.txt': 0.00513281304394720, 'breccia.txt': 0.00501607343520665}
P2 {}
P3 {'amphibolite.txt': 0.00484181658252891, 'siltstone.txt': 0.00486999982527626}
P4 {'amphibolite.txt': 0.00489936166850968, 'siltstone.txt': 0.00494558784770914}

[{'amphibolite.txt': 0.00593448307396262, 'basalt.txt': 0.00513281304394720, 'breccia.txt': 0.00501607343520665}, {}, {'amphibolite.txt': 0.00484181658252891, 'siltstone.txt': 0.00486999982527626}, {'amphibolite.txt': 0.00489936166850968, 'siltstone.txt': 0.00494558784770914}]

Below is a combination of dictionary files from P1 to P4 as inventory. Among the values that come out like that, I would like to express it as one key by adding the same values in a dictionary with the same key value, such as amphibolite.txt. Help me

python dictionary

2022-09-21 16:02

1 Answers

Pandas are very comfortable.

>>> import pandas as pd

>>> df = pd.DataFrame([{'amphibolite.txt': 0.00593448307396262, 'basalt.txt': 0.00513281304394720, 'breccia.txt': 0.00501607343520665}, {}, {'amphibolite.txt': 0.00484181658252891, 'siltstone.txt': 0.00486999982527626}, {'amphibolite.txt': 0.00489936166850968, 'siltstone.txt': 0.00494558784770914}])
>>> df
   amphibolite.txt  basalt.txt  breccia.txt  siltstone.txt
0         0.005934    0.005133     0.005016            NaN
1              NaN         NaN          NaN            NaN
2         0.004842         NaN          NaN       0.004870
3         0.004899         NaN          NaN       0.004946
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 4 columns):
amphibolite.txt    3 non-null float64
basalt.txt         1 non-null float64
breccia.txt        1 non-null float64
siltstone.txt      2 non-null float64
dtypes: float64(4)
memory usage: 208.0 bytes
>>> df.describe()
       amphibolite.txt  basalt.txt  breccia.txt  siltstone.txt
count         3.000000    1.000000     1.000000       2.000000
mean          0.005225    0.005133     0.005016       0.004908
std           0.000615         NaN          NaN       0.000053
min           0.004842    0.005133     0.005016       0.004870
25%           0.004871    0.005133     0.005016       0.004889
50%           0.004899    0.005133     0.005016       0.004908
75%           0.005417    0.005133     0.005016       0.004927
max           0.005934    0.005133     0.005016       0.004946
>>> df.sum()
amphibolite.txt    0.015676
basalt.txt         0.005133
breccia.txt        0.005016
siltstone.txt      0.009816
dtype: float64
>>> df.product()
amphibolite.txt    1.407767e-07
basalt.txt         5.132813e-03
breccia.txt        5.016073e-03
siltstone.txt      2.408501e-05
dtype: float64


2022-09-21 16:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.