Python | Панды Series.to_json ()

Опубликовано: 28 Марта, 2022

Серия Pandas - это одномерный массив ndarray с метками осей. Этикетки не обязательно должны быть уникальными, но должны быть хешируемого типа. Объект поддерживает индексирование как на основе целых чисел, так и на основе меток и предоставляет множество методов для выполнения операций, связанных с индексом.

Pandas Series.to_json() function is used to convert the object to a JSON string. Also note that NaN’s and None will be converted to null and datetime objects will be converted to UNIX timestamps.

Syntax: Series.to_json(path_or_buf=None, orient=None, date_format=None, double_precision=10, force_ascii=True, date_unit=’ms’, default_handler=None, lines=False, compression=’infer’, index=True)

Parameter :
path_or_buf : File path or object. If not specified, the result is returned as a string.
orient : Indication of expected JSON string format.
date_format : None, ‘epoch’, ‘iso’}
double_precision : The number of decimal places to use when encoding floating point values.
force_ascii : Force encoded string to be ASCII.
date_unit : string, default ‘ms’ (milliseconds)
default_handler : callable, default None
lines : bool, default False
compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}

Returns : Json string

Example #1: Use Series.to_json() function to convert the given series object to JSON string.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(["New York", "Chicago", "Toronto", "Lisbon", "Rio", "Moscow"])
  
# Create the Datetime Index
didx = pd.DatetimeIndex(start ="2014-08-01 10:00", freq ="W"
                     periods = 6, tz = "Europe/Berlin"
  
# set the index
sr.index = didx
  
# Print the series
print(sr)

Выход :

Now we will use Series.to_json() function to convert the given series object to JSON string.

# convert to JSON string
sr.to_json()

Выход :

As we can see in the output, the Series.to_json() function has successfully converted the given series object to JSON string.

Example #2: Use Series.to_json() function to convert the given series object to JSON string.

Выход :

Now we will use Series.to_json() function to convert the given series object to JSON string.

# convert to JSON string
sr.to_json()

Выход :

As we can see in the output, the Series.to_json() function has successfully converted the given series object to JSON string.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.