Pandas 循环以迭代并将数据帧分割为块,然后写入csv
我有一个导入到Pandas中的文件,我从csv中读取该文件,需要根据iloc将其分为多个块。该文件有100000个,我想要一个for循环,将每个分割文件一次性写入单个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
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