Reputation: 23
I have two CSV files. Let them be source.csv
and dest.csv
source.csv:
A B C D
1 3 6 3
1 4 3 1
2 4 1 6
1 3 5 7
dest.csv:
E F G H
1 3 5 2
1 3 4 2
1 5 2 4
1 3 5 2
I'm trying to copy the B'th column from source.csv
and append it after the column F(position 2) of dest.csv
so that the dest.csv
will look like this
dest.csv:
E F B G H
1 3 3 5 2
1 3 4 4 2
1 5 4 2 4
1 3 3 5 2
Huge thank you to any help provide.
Upvotes: 1
Views: 251
Reputation: 23
i got the answer.!!
def patch(count_of_files):
stitch_key = "BatchOutput_" + str(count_of_files)
files_name = []
for files in os.listdir(directory): # Loping through directory and taking each files to add to files_name
if stitch_key in files:
files_name.append(files)
df = pd.read_csv(directory+"/"+files_name[0], index_col=False)
for i in files_name:
if i == files_name[0]: # continuing loop for first file
continue
df_temp = pd.read_csv(directory+"/"+i, index_col=False)
columns_name = df_temp.columns.values.tolist() # taking all column names into a list
columns_name = columns_name[7:10]
percentile_0 = df_temp.iloc[:, [7]]
percentile_1 = df_temp.iloc[:, [8]]
percentile_2 = df_temp.iloc[:, [9]]
df.insert(7, columns_name[0], percentile_0,allow_duplicates=True) # inserting percentiles into dataframe
df.insert(7, columns_name[1], percentile_1,allow_duplicates=True)
df.insert(7, columns_name[2], percentile_2,allow_duplicates=True)
df.to_csv(directory+"/"+files_name[0], index=False) # converting the dataframe into output csv
for files in files_name:
if files == files_name[0]:
continue
os.remove(directory+"/"+files)
Upvotes: 0
Reputation: 192
First, you need to read the files, then insert the column and finally save the df as a new csv file:
import pandas as pd
df_source = pd.read_csv('source.csv')
df_dest = pd.read_csv('dest.csv')
df_dest.insert(2,'B',df_source['B']) #This modifies df_dest in place.
df_dest.to_csv('dest_output.csv)
Note that this will only work if both files (source and dest) are in the same location where you are running your script. If not, provide the full paths when reading with the read_csv method. (I.e.: read_csv('PATH)
).
Upvotes: 1