Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

python - How to split a csv file into multiple csv based on a given criterion?

I need to split few csv files based on a given time. In these files the time values are in seconds and given in 'Time' column.

For example, if I want to split aaa.csv file in 0.1 seconds, then the first set of rows with time 0.0 to 0.1 (No 1 to 8 in attached file) needs to get written into aaa1.csv, then the rows with time greater than 0.1 to 0.2 (No. 9 to 21 in attached file) to aaa2.csv so on...(basically multiples of the given time).

Output files needs to get the same name as input file along with a number at the end. And output files need to get written into a different location/folder. Time value need to be a variable. So at a time I can split in 0.1 sec and at another time I can split the file in 0.7sec so on.

How can I write a python script for this please? The file looks like the following (entire 119K file can be downloaded from https://fil.email/vnsZsp7b):

No.,Time,Length
1,0,146
2,0.006752,116
3,0.019767,156
4,0.039635,144
5,0.06009,147
6,0.069165,138
7,0.0797,133
8,0.099397,135
9,0.120142,135
10,0.139721,148
11,0.1401,126
12,0.1401,120
13,0.140101,123
14,0.140101,120
15,0.141294,118
16,0.141295,118
17,0.141295,114
18,0.144909,118
19,0.160639,119
20,0.161214,152
21,0.185625,143
... etc

AFTER @Serafeim 's answer, I tried this:

import pandas as pd
import numpy as np
import glob
import os

path = '/root/Desktop/TT1/'
mystep = 0.4


for filename in glob(os.path.join(path, '*.csv')):
    df = pd.read_csv(filename)
    def data_splitter(df):
        max_time = df['Time'].max() # get max value of Time for the current csv file (df)
        myrange= np.arange(0, max_time, mystep) # build the threshold range
        for k in range(len(myrange)):
            # build the upper values
            temp = df[(df['Time'] >= myrange[k]) & (df['Time'] < myrange[k] + mystep)]
            #temp.to_csv("/root/Desktop/T1/xx_{}.csv".format(k))
            temp.to_csv("/root/Desktop/T1/{}_{}.csv".format(filename, k))

data_splitter(df)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just need to apply a logical operation on the dataframe using pandas. ??

At the end of this answer I have a "script idea" to do this automatically but first let's go Step by step:

# Load the files using pandas
import pandas as pd

df = pd.read_csv("/Users/serafeim/Downloads/Testfile.csv")

# Get the desired elements based on 'Time' column
mask = df['Time'] < 0.1

# Write the new file
df_1 = df[mask] # or directly use: df_1 = df[df['Time'] < 0.1]

# save it 
df_1.to_csv("Testfile1.csv")

print(df_1)
    No.      Time  Length
0    1  0.000000     146
1    2  0.006752     116
2    3  0.019767     156
3    4  0.039635     144
4    5  0.060090     147
5    6  0.069165     138
6    7  0.079700     133
7    8  0.099397     135

#For 0.1 to 0.2 applying 2 logical conditions
df_2 = df[(df['Time'] > 0.1) & (df['Time'] < 0.2)]

The script idea:

import pandas as pd
import numpy as np

mystep = 0.2 # the step e.g. 0.2, 0.4, 0.6 

#define the function
def data_splitter(df):
    max_time = df['Time'].max() # get max value of Time for the current csv file (df)
    myrange= np.arange(0, max_time, mystep) # build the threshold range
    for k in range(len(myrange)):
        # build the upper values 
        temp = df[(df['Time'] >= myrange[k]) & (df['Time'] < myrange[k] + mystep)]
        temp.to_csv("/Users/serafeim/Downloads/aaa_{}.csv".format(k))

Now, call the function:

df = pd.read_csv("/Users/serafeim/Downloads/Testfile.csv")
data_splitter(df) # pass the df to the function and call the function

Finally, you can create a loop and pass each df one by one in the data_splitter() function.

To make more clear what the function does look this:

for k in range(len(myrange)):
    print myrange[k], myrange[k]+step

This prints:

0.0 0.2
0.2 0.4
0.4 0.6000000000000001
0.6000000000000001 0.8
0.8 1.0

So it creates the lower & upper thresholds automatically based on the max value of Time column of the current .csv file.

EDIT 2:

import glob, os
path = '/Volumes/'

mystep = 0.2 

for filename in glob.glob(os.path.join(path, '*.csv')):
    df = pd.read_csv(filename)
    data_splitter(df)

PUTTING ALL TOGETHER:

import pandas as pd
import numpy as np
import glob
import os

path = '/root/Desktop/TT1/'
mystep = 0.4

#define the function
def data_splitter(df, name):
    max_time = df['Time'].max() # get max value of Time for the current csv file (df)
    myrange= np.arange(0, max_time, mystep) # build the threshold range
    for k in range(len(myrange)):
        # build the upper values 
        temp = df[(df['Time'] >= myrange[k]) & (df['Time'] < myrange[k] + mystep)]
        temp.to_csv("/root/Desktop/T1/{}_{}.csv".format(name, k))

for filename in glob.glob(os.path.join(path, '*.csv')):
    df = pd.read_csv(filename)
    name = os.path.split(filename)[1] # get the name of the file
    data_splitter(df, name) # call the splitting function


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...