1

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)
Chris
  • 15,819
  • 3
  • 24
  • 37
JEG
  • 154
  • 1
  • 15
  • I don't think anyone can provide you with the actual code of how to achieve this, without you providing a minimal example of a csv file data. Either way, the idea is that you should store the name of the file, I guess `forecaster` and then when changing the dataframe column name, just have assigned to the new name. – Newskooler Jul 08 '19 at 14:08
  • can't you add something like "wind": "wind_{}".format(forecaster.split(.)[0]) to your rename call – Chris Jul 08 '19 at 14:10
  • Assuming path_pre at each iteration is 'Dar.csv' etc... you can just do: `suffix = forecaster.split('.')[0]` and then `dataframe.columns = [el + suffix for el in dataframe.columns]` to replace the line where you rename the columns. – Buckeye14Guy Jul 08 '19 at 14:10

1 Answers1

1

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]
vlemaistre
  • 3,301
  • 13
  • 30