Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 循环以迭代并将数据帧分割为块,然后写入csv_Pandas_Loops - Fatal编程技术网

Pandas 循环以迭代并将数据帧分割为块,然后写入csv

Pandas 循环以迭代并将数据帧分割为块,然后写入csv,pandas,loops,Pandas,Loops,我有一个导入到Pandas中的文件,我从csv中读取该文件,需要根据iloc将其分为多个块。该文件有100000个,我想要一个for循环,将每个分割文件一次性写入单个csv。我正在寻找实现自动化的最佳方法,下面是我的示例代码 import pandas as pd test=pd.read_csv("test.csv") test1=test.iloc[0:25000] test2=test.iloc[25001:50000] test3=test.iloc[50001:7

我有一个导入到Pandas中的文件,我从csv中读取该文件,需要根据iloc将其分为多个块。该文件有100000个,我想要一个for循环,将每个分割文件一次性写入单个csv。我正在寻找实现自动化的最佳方法,下面是我的示例代码

import pandas as pd
test=pd.read_csv("test.csv")

test1=test.iloc[0:25000]
test2=test.iloc[25001:50000]
test3=test.iloc[50001:75000]
test4=test.iloc[75001:100000]

test1.to_csv("test1.csv")
test2.to_csv("test2.csv")
test3.to_csv("test3.csv")
test4.to_csv("test4.csv")
test=pd.read\u csv(“test.csv”)
最大行数=100000
页面大小=25000
当前页面=0
当前页面*页面大小<最大行数:
chunk=test.iloc[当前页面*页面大小:当前页面*页面大小+页面大小-1]
chunk.to_csv(f“test{current_page+1}.csv”)
当前页面=当前页面+1

这样,您只需设置页面大小和最大行数,它就可以在页面上迭代,为每个页面创建一个块并保存它

您可以通过创建自定义索引来使用groupby

for grp, each_csv in df.groupby(df.index // 4):
    each_csv.to_csv(f"test_{grp}.csv",index=False)
以下数据帧将产生:

     A
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
10  10

     A
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
10  10