I have many CSV files and I would like to rename each column of each file. A CSV file has for example a column named "wind" and I would like to transform it automatically to : wind_Dar. (Dar is the name of one file) so in other words I would like that each column of each file has the label "column name"_"currentFilename"
Here is my code :
path = ".../As-Pre-"
path_previsions = ["Dar.csv","Ope.csv","Wea.csv", "Wun.csv"]
path_observations = ".../As-Ob.csv"
def get_forecast(path, path_pre, path_ob):
list_data = []
for forecaster in path_pre:
dataframe = pd.read_csv(path + forecaster, sep=";").dropna(subset=["temperature"])
dataframe["time"] = dataframe["time"].apply(lambda x: str(x).split(":")[0])
dataframe = dataframe.groupby(['time']).mean()
dataframe = dataframe.rename(index=str, columns={"humidity": "humidity_Y", "precipitation": "precipitation_Y",
"temperature":"temperature_Y"})
list_data.append(dataframe)
I'm not sure where your code fails. But here is an easy way to rename the columns the way you want to using a list comprehension :
dataframe.columns = [x + forecaster.split('.')[0] for x in dataframe.columns]