Here is a sample data of a dataframe:
df:
df = pd.DataFrame(columns=['id', 'value', 'sum'])
+-----+-----+-------+------+
| | id | value | sum |
+-----+-----+-------+------+
| 1 | 115 | 4 | 6 |
+-----+-----+-------+------+
| 2 | 115 | 23 | 57 |
+-----+-----+-------+------+
| 3 | 18 | 143 | 253 |
+-----+-----+-------+------+
| 4 | 18 | 5 | 9 |
+-----+-----+-------+------+
| 5 | 22 | 86 | 144 |
+-----+-----+-------+------+
| 6 | 22 | 104 | 209 |
+-----+-----+-------+------+
| 7 | 22 | 909 | 2132 |
+-----+-----+-------+------+
| ... | ... | ... | ... |
+-----+-----+-------+------+
It gives me output like this in json:
df = {'115': [4, 6], '115': [23, 57], '18': [143, 253], '18': [5, 9],
'22': [86, 144], '22': [104, 209], '22': [909, 2132], ... }
I would like to combine values of the same id like below in another dataframe:
dft = pd.DataFrame(columns=['id', 'total'])
+-----+-----+----------------------------------+
| | id | total |
+-----+-----+----------------------------------+
| 1 | 115 | [4, 6] [23, 57] |
+-----+-----+----------------------------------+
| 3 | 18 | [143, 254] [5, 9] |
+-----+-----+----------------------------------+
| 5 | 22 | [86, 144] [104, 209] [909, 3132] |
+-----+-----+----------------------------------+
| ... | ... | ... |
+-----+-----+----------------------------------+
dft = {'115': [[4, 6], [23, 57]], '18': [[143, 253], [[5, 9]]
'22': [[86, 144], [104, 209], [909, 2132]], ... }
I tried the below code but it does not work:
dft = pd.DataFrame(columns=['id', 'total'])
pid = 0
for i in df['id']:
if pid == df['id']:
dft.loc[['id']] = df['id']
dft.loc[['total']] = [ df[['id'],['value']] + df[['id'],['sum']] ]
pid = df['index'][id] + 1
import json
with open('total.json', 'w') as fp:
json.dump(dft, fp)
It is not working and gives errors.
df = pd.DataFrame({'id': {1: 115, 2: 115, 3: 18, 4: 18, 5: 22, 6: 22, 7: 22},
'value': {1: 4, 2: 23, 3: 143, 4: 5, 5: 86, 6: 104, 7: 909},
'sum': {1: 6, 2: 57, 3: 253, 4: 9, 5: 144, 6: 209, 7: 2132}})
df['total'] = df.set_index('id').values.tolist()
df = df.groupby('id')['total'].apply(list).reset_index()
with open('data.json', 'w') as f:
json.dump(dict(zip(df.id,df.total)), f)
Output
'{"18": [[143, 253], [5, 9]], "22": [[86, 144], [104, 209], [909, 2132]], "115": [[4, 6], [23, 57]]}'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.