[英]How to rename each dataframe from a list of names
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.在这里,我从目录中加载了所有 csvs 并保存了它们。
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.这些是我想调用每个对应的 dataframe 的名称。
list_of_dataframes is another list with all dataframes appended. list_of_dataframes 是附加了所有数据帧的另一个列表。
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.所以我希望能够通过其 csv 名称调用每个数据帧。
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.如果我理解正确,您有一个 Dataframe
df
链接到其数据来源的filename
。 I would use a dict
in this case since you already have the name<->value
.在这种情况下,我会使用
dict
,因为您已经有了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..您可以创建 dataframe 字典并通过
df['circuits']
等访问所有数据框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.