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!
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.
Comments