Write a Python code to create a series with your range values, generate a new row as sum of all the values and then convert the series into json file

To create a Pandas series with range values, add a sum row, and convert to JSON format, we need to follow a structured approach using pandas library functions.

Solution

To solve this, we will follow the steps given below −

  • Define a series with a range of 1 to 10

  • Find the sum of all the values

  • Convert the series into JSON file format

Let us see the following implementation to get a better understanding ?

Example

import pandas as pd

# Create a series with range values from 1 to 10
data = pd.Series(range(1, 11))
print("Original Series:")
print(data)
print()

# Add sum as a new row
data['sum'] = data.sum()
print("Series with sum row:")
print(data)
print()

# Convert to JSON format
json_result = data.to_json()
print("JSON representation:")
print(json_result)

Output

Original Series:
0     1
1     2
2     3
3     4
4     5
5     6
6     7
7     8
8     9
9    10
dtype: int64

Series with sum row:
0       1
1       2
2       3
3       4
4       5
5       6
6       7
7       8
8       9
9      10
sum    55
dtype: int64

JSON representation:
{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"7":8,"8":9,"9":10,"sum":55}

How It Works

The pd.Series(range(1, 11)) creates a series with values 1 through 10. Using data['sum'] = data.sum() adds a new row with key 'sum' containing the total of all numeric values. The to_json() method converts the series into JSON string format where indices become keys and values remain as values.

Conclusion

This approach demonstrates how to create a Pandas series, add computed values, and export to JSON format. The series automatically handles the sum calculation and JSON conversion preserves both numeric and string indices.

Updated on: 2026-03-25T15:52:17+05:30

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements