i have a CSV file which name is data.CSV and i want to make column from file name for example data is column and value must be data as well how can i do this?
import pandas as pd
import glob
files = glob.glob('path to dir/*.csv')
df = None
for i, f in enumerate (files):
if i == 0:
df = pd.read_csv(f)
df['fname'] = f
else:
tmp = read_csv(f)
tmp['fname'] = f
df = df.append(tmp)
df.head()
-
$\begingroup$ i got a error of invalid syntax can u help me solve this problem? $\endgroup$ – subash poudel Oct 29 '18 at 15:38
-
You could use os.listdir()
in order to get the file name:
import os
file_name = os.listdir() # you need to use the path to the directory of the file
file_name_noext = file_name.replace(".csv", "") # in order to remove the .csv part
Now if you have a DataFrame
called data
:
import pandas as pd
data = pd.DataFrame()
data[file_name_noext] = file_name_noext # to update the dataframe