I've searched online a lot but it wasn't useful. That's where I'm stuck:
path = os.getcwd() # define path
csv_files = glob.glob(os.path.join(path, "*.csv")) # read all files with suffix csv
list_of_dataframes = [] # create empty array
names = []
for f in csv_files:
df = pd.read_csv(f)
list_of_dataframes.append(df) # add all dfs in this object
names.append(f.split("\\")[-1].replace(".csv", "")) # double slash to set where to split data (try without to understand)
# -1 to get final part of string (they are paths)
# command strip, lstrip and rstrip is not useful, let's use replace
print(f.split("\\")[-1].replace(".csv", ""))
Here I loaded all the csvs from directory and saved them.
In names I have this:
['circuits',
'constructors',
'constructor_results',
'constructor_standings',
'drivers',
'driver_standings',
'lap_times',
'pit_stops',
'qualifying',
'races',
'results',
'seasons',
'sprint_results',
'status']
These are the names I want to call each corresponding dataframe.
list_of_dataframes is another list with all dataframes appended.
What I want to achieve is:
circuits = list_of_dataframes[0]
constructors = list_of_dataframes[1]
...
So I want to be able to call each dataframes by its csv name.
I've tried that but it's not working as I would:
for i in range(len(list_of_dataframes)):
names[i] = pd.DataFrame(list_of_dataframes[i])
Honestly, your problem statement is quite confuse for me.
If I understand correctly, you have a Dataframe df
that is linked to the filename
where its data came from. I would use a dict
in this case since you already have the name<->value
. Thus:
dfs={}
for filename in ....:
dfs[filename]=pd.read_csv(filename)
path = os.getcwd() # define path
csv_files = glob.glob(os.path.join(path, "*.csv")) # read all files with suffix csv
df = {}
for f in csv_files:
fileName = f.split("\\")[-1].replace(".csv", "")
df[fileName] = pd.read_csv(f)
you can create dictionary of dataframe and accessed all your data frame by df['circuits']
etc..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.