从 pandas df到csv只写前N行 [英] WRITE only first N rows from pandas df to csv

查看:46
本文介绍了从 pandas df到csv只写前N行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不首先将df子集化的情况下从熊猫数据帧仅将前N行或从P到Q行写入到csv中的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.

我正在考虑一个逐行写入csv的函数.

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

谢谢

推荐答案

  • 使用 head-返回前n行.
    • Use head- Return the first n rows.
    • 例如.

      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"))
      

      这篇关于从 pandas df到csv只写前N行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆