Reputation: 145
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)
Upvotes: 2
Views: 3045
Reputation: 33182
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)
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
Upvotes: 3
Reputation: 551
Assume that you have 2 directories: Source and Test. Source contains all the source csv files and the Test directory will have all the output files.
import os
import glob
os.chdir("/home/prasanth-8508/Downloads/Source")
for csv_file in glob.glob("*.csv"):
contents, output_list = list(), list()
with open(csv_file) as f:
contents.append(f.read().replace('"', ""))
contents = ''.join(contents).split('\n')
header = contents[0]
contents = contents[1:]
op_file_counter = 1
split_factor = float(input("Enter split factor:"))
split_num = split_factor
i = 0
contents = list(filter(None, contents))
while i < len(contents)-1:
try:
row = contents[i].split(",")
if not(str(float(row[1])).startswith(str(split_num)[0:str(split_num).index(".")+2], 0, str(split_num).index(".")+2)):
output_list.append(contents[i])
i += 1
else:
if len(output_list) > 0:
with open("/home/prasanth-8508/Downloads/Test/file" + str(op_file_counter) + ".csv", "a+") as f:
f.write(header+'\n')
for j in output_list:
f.write(j+'\n')
op_file_counter += 1
output_list = list()
split_num += split_factor
split_num = round(split_num,1)
print(split_num)
except IndexError:
break
with open("/home/prasanth-8508/Downloads/Test/file" + str(op_file_counter) + ".csv", "a+") as f:
f.write(header+'\n')
for j in output_list:
f.write(j+'\n')
print(csv_file+" processed successfully")
I got more than 600 files after running the program which is too large to be shared.
Upvotes: -1