Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WRITE only first N rows from pandas df to csv

Tags:

python

pandas

csv

How can I write only first N rows or from P to Q rows to csv from pandas dataframe without subseting the df first? I cannot subset the data I want to export because of memory issues.

I am thinking of a function which writes to csv row by row.

Thank you

like image 389
criticalth Avatar asked Aug 12 '19 09:08

criticalth


People also ask

How do you get the first 5 rows in pandas?

You can use df. head() to get the first N rows in Pandas DataFrame. Alternatively, you can specify a negative number within the brackets to get all the rows, excluding the last N rows.

How do you select the first n rows in a DataFrame?

DataFrame. head(n) to get the first n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the start). By default n = 5, it return first 5 rows if value of n is not passed to the method.


1 Answers

  • Use head- Return the first n rows.

Ex.

import pandas as pd
import numpy as np
date = pd.date_range('20190101',periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=date, columns=list('ABCD'))

#wtire only top two rows into csv file
print(df.head(2).to_csv("test.csv"))
like image 88
bharatk Avatar answered Oct 19 '22 06:10

bharatk