Reputation: 11
I have to read in multiple files and store these files as df in memory, since there are no headers in my csv file, I need to add multiple headers to each df manually. Each file has different headers.
What I did is using the if-elif statements, which works but very redundant. Does anyone have any idea how to make it more compact/smart?
if file_name == "20210101":
headers = ["Name","Age","City"]
df = df.read_csv(data, sep=";"dtype= str, names = headers)
elif file_name == "20210102":
headers = ["Age","Location","Nation"]
df = df.read_csv(data, sep=";"dtype= str, names = headers)
elif file_name == "20210103":
headers = ["Account","Position","Sex"]
df = df.read_csv(data, sep=";"dtype= str, names = headers)
Upvotes: 1
Views: 116
Reputation: 78790
Use a dictionary mapping filenames to headers.
headers = {"20210101": ["Name","Age","City"], ...}
df = pd.read_csv(file_name, names=headers[file_name], ...)
Upvotes: 2