📅  最后修改于: 2023-12-03 15:03:28.591000             🧑  作者: Mango
When working with data in Pandas, it's common to convert the data to JSON format for easy storage and transfer. However, by default, the to_json()
function includes the index of the DataFrame. This can be a problem if you don't want to include the index in your JSON file. In this tutorial, we'll show you how to convert a Pandas DataFrame to JSON without the index.
To convert a Pandas DataFrame to JSON without the index, you need to use the orient
parameter of the to_json()
function. The orient
parameter specifies the format of the JSON file you want to output. By default, orient
is set to index
, which includes the index in the output.
To exclude the index from the output, you can set orient
to records
. This will output a JSON file where each row of the DataFrame is represented as a separate record with no index.
Here's an example:
import pandas as pd
# create a sample DataFrame
df = pd.DataFrame({
'name': ['John', 'Anna', 'Peter'],
'age': [25, 32, 19]
})
# convert the DataFrame to JSON without the index
json_output = df.to_json(orient='records')
# print the output
print(json_output)
Output:
[{"name":"John","age":25},{"name":"Anna","age":32},{"name":"Peter","age":19}]
As you can see, the resulting JSON file does not include the index.
Converting a Pandas DataFrame to JSON without the index is easy using the to_json()
function with the orient
parameter set to records
. This will output a JSON file where each row of the DataFrame is represented as a separate record with no index.