Book Image

Mastering pandas - Second Edition

By : Ashish Kumar
Book Image

Mastering pandas - Second Edition

By: Ashish Kumar

Overview of this book

pandas is a popular Python library used by data scientists and analysts worldwide to manipulate and analyze their data. This book presents useful data manipulation techniques in pandas to perform complex data analysis in various domains. An update to our highly successful previous edition with new features, examples, updated code, and more, this book is an in-depth guide to get the most out of pandas for data analysis. Designed for both intermediate users as well as seasoned practitioners, you will learn advanced data manipulation techniques, such as multi-indexing, modifying data structures, and sampling your data, which allow for powerful analysis and help you gain accurate insights from it. With the help of this book, you will apply pandas to different domains, such as Bayesian statistics, predictive analytics, and time series analysis using an example-based approach. And not just that; you will also learn how to prepare powerful, interactive business reports in pandas using the Jupyter notebook. By the end of this book, you will learn how to perform efficient data analysis using pandas on complex data, and become an expert data analyst or data scientist in the process.
Table of Contents (21 chapters)
Free Chapter
1
Section 1: Overview of Data Analysis and pandas
4
Section 2: Data Structures and I/O in pandas
7
Section 3: Mastering Different Data Operations in pandas
12
Section 4: Going a Step Beyond with pandas

Writing JSON objects to a file

The to_json() function allows any DataFrame object to be converted into a JSON string or written to a JSON file if the file path is specified:

df = pd.DataFrame({"Col1": [1, 2, 3, 4, 5], "Col2": ["A", "B", "B", "A", "C"], "Col3": [True, False, False, True, True]})
df.to_json()

Take a look at the following output:

JSON output

The orientation of the data in the JSON can be altered. The to_json() function has an orient argument which can be set for the following modes: columns, index, record, value, and split. Columns is the default setting for orientation:

df.to_json(orient="columns")

Take a look at the following output:

JSON output column orientation

Orienting along the index acts like a transpose of the former case with a reversal of row and column...