0

I have a single csv file chr1.step1.csv, say it has five columns. I can read this as follows:

df=pd.read_csv('chr1.step1.csv',sep='\t',header=None)
df.head()
0 1 2 3 4 5
a1 b1 c1 d1 e1
a2 b2 c2 d2 e2
a3 b3 c3 d3 e3

How can I add 6th column as file name chr1.step1.csv, such as:

0 1 2 3 4 5 6
a1 b1 c1 d1 e1 chr1.step1.csv
a2 b2 c2 d2 e2 chr1.step1.csv
a3 b3 c3 d3 e3 chr1.step1.csv

Its only one file, not multiple files.

3
  • 3
    df[6] = "chr1.step1.csv"? Commented May 9, 2021 at 0:06
  • Thanks. But I need to take the argument from file name. Commented May 9, 2021 at 0:46
  • 2
    like filename='chr1.step1.csv'; df=pd.read_csv(filename,sep='\t',header=None); df[6]=filename? i think that's basically all you can do Commented May 9, 2021 at 1:24

1 Answer 1

5

Assuming that 6th column name is Name File, and considering the file is in the path csv = '/home/User/Documents/file.csv' or csv = 'file.csv', one can do that using the os.path module.

import os.path

df['Name File'] = os.path.basename(csv)

One might also do, as @tdy suggests. Assign the name of the file to a variable

filename='chr1.step1.csv'; 

Then, assuming the df already exists (else one needs to read it, with something like df=pd.read_csv(filename,sep='\t',header=None)), assign the file name to the cells in a new column

df['Name File'] = filename

Extra: If one has a directory with lots of csv files

import pandas as pd
import glob
import os.path

# Create a list of all CSV files
files = glob.glob("*.csv")

# Create an empty list to append the df
filenames = []

for csv in files:
    df = pd.read_csv(csv)
    df['Name File'] = os.path.basename(csv)
    filenames.append(df)
Sign up to request clarification or add additional context in comments.

1 Comment

With your 'extra' you need to add a concat to bring the dfs together.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.