To convert a pandas DataFrame into a JSON string in Python, you can use the to_json method provided by pandas. Here's how you can use it:
import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'Name': ['John', 'Anna', 'Eva'], 'Age': [28, 22, 32], 'City': ['New York', 'Paris', 'Berlin'] }) # Convert to JSON json_result = df.to_json() print(json_result) The to_json function provides the orient parameter to specify the format or "shape" of the resulting JSON string:
'split': Dictionary containing indexes, columns, and data.'records': List of dictionaries with each item representing a row.'index': Row-oriented format with dictionaries using DataFrame indexes.'columns': Column-oriented format with dictionaries using DataFrame columns.'values': Just the values in a 2D array.'table': Schema format (useful for databases).For example:
json_records = df.to_json(orient='records') print(json_records)
If your DataFrame contains datetime objects, you can use the date_format parameter to specify how dates should be formatted in the resulting JSON:
'epoch': Default, represent dates as UNIX timestamps.'iso': ISO8601 format.df_dates = pd.DataFrame({'date': pd.to_datetime(['2021-01-01', '2021-02-01'])}) json_dates = df_dates.to_json(date_format='iso') print(json_dates) If you'd like to write the resulting JSON directly to a file, you can use the to_json method with a file path:
df.to_json('output.json') This will create an output.json file with the DataFrame content in JSON format.
These are just a few examples of the capabilities of the to_json method. Refer to the pandas documentation for more details and options.
savechanges digital-signature xaml prompt sasl gantt-chart elasticsearch-aggregation nsmutableattributedstring itunes scrollbar