print top 3 Pandas DataFrame rows to JSON

Rohit

I would like to print (or return) just 3 top rows of a pandas DataFrame. Doing the following gets me all of them:

df1 = pd.DataFrame(np.random.randn(10,2),columns=list('AB'))
df2 = df1.sort(["B"], ascending=[True]) 

df2.to_json(orient="records")  # prints all the rows

How do I limit JUST the top 3 rows and print them to JSON?

Thanks!

user3754068

You should be able to use head and pass the number of lines to include

short_list = df2.head(3).to_json(orient="records")

Output:

'[
  {"A":-0.4056731092,"B":-1.2808121187},
  {"A":-0.1866904667,"B":-1.2226082762},
  {"A":0.462008584,"B":-1.070959354}
 ]'

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

picking rows in pandas dataframe with top scores

From Dev

Getting top 3 rows that have biggest sum of columns in `pandas.DataFrame`?

From Dev

Import and Print Json objects in Dataframe in Pandas

From Dev

pandas calculate rolling_std of top N dataframe rows

From Dev

Return top n rows based on threshold from pandas dataframe

From Dev

Pandas (0.16.2) Show 3 Rows of Dataframe

From Dev

How to print rows if values appear in any column of pandas dataframe

From Dev

pandas: print all non-empty rows from a DataFrame

From Dev

displaying the top 3 rows

From Dev

Getting top 3 values from multi-index pandas dataframe

From Dev

Top 3 items to be shown in wide format in pandas dataframe

From Dev

Print Pandas dataframe with index

From Dev

Pandas parse json in column and expand to new rows in dataframe

From Dev

Pandas parse json in column and expand to new rows in dataframe

From Dev

Python pandas DataFrame - Keep rows that have same information in 3 columns

From Dev

Take long list of items and reshape into dataframe "rows" - pandas python 3

From Dev

Splitting DataFrame rows with pandas

From Dev

Delete Rows in pandas dataframe

From Dev

Truncate rows of a pandas DataFrame

From Dev

combining rows in pandas dataframe

From Dev

Substraction of rows in pandas dataframe

From Dev

multiplying rows in a pandas dataframe

From Dev

Normalizing rows of pandas dataframe

From Dev

Pandas Series - print columns and rows

From Dev

postgresql count the top 3 rows

From Dev

Top 3 rows per country

From Dev

add a row at top in pandas dataframe

From Dev

Finding top 10 in a dataframe in Pandas

From Dev

Debugging a print DataFrame issue in Pandas

Related Related

HotTag

Archive