I want to add to my dictionary dfList
an id and a dataframe. But my adding doesn't work. How could I add to my dictionary the id and the df, that later I want to say give me from the dictionary dfList
the dataframe
with the id
file1.csv
.
So how could I add this in a loop and later give me the rom the dictionary dfList
the dataframe
with the id
file1.csv
back?
csvfiles = ['file1.csv', 'file2.csv']
dfList = []
for index, csvfile in enumerate(csvfiles):
file = os.path.join('C:/Documents', csvfile)
df = pd.read_csv(file)
#dfList[index]['id'] = csvfiles
#dfList[index]['dataframe'] = df
dfList.append(dfList['id'] = csvfiles)
What I want at the end
dfList = [{'id': 'file1.csv', 'dataframe': df}, {'id': 'file2.csv', 'dataframe': df}]
The below code is for testing. In case you want to try something out. Here is a min. code for Testing. If you want to try:
d = {'id': [1, 2, 3, 4], 'horstid': [11, 22, 33, 33]}
df = pd.DataFrame(data=d)
d2 = {'id': [1, 2, 3, 4]]}
df2 = pd.DataFrame(data=d2)
csvfiles = [df, df2]
dfList = []
for index, csvfile in enumerate(csvfiles):
#dfList[index]['id'] = str("File" index)
#dfList[index]['dataframe'] = csvfile
# What I want is
# Get the dataframe with the id File1
# df_new = dfList[df = (dfList['id] == 'File1')]
# df_new
# [OUT]
# id horstid
# 0 1 11
# 1 2 22
# 2 3 33
# 3 4 33
CodePudding user response:
I think you want this structure:
{'file1.csv': <df1>, 'file2.csv': <df2> ... }
Dont use a list. Use a dictionary. Use the file name as key and the data frame as value:
dDict[csvfile] = df
Then get the dataframe by its filename:
dDict[filename] # --> <data>