Search code examples
pythonpandasdataframecsvexport-to-csv

Is there a way to combine rows in a Pandas DataFrame, given the row index?


I am looking to combine row 2 with row 0, so that the unit of the row is part of the column header and not following the data point. The data comes from a .csv file in this format, but it would be much easier to work with if the unit was in the header. The unit is not always "mi/h" and can change in any given reference file. Sections like these have been extracted from larger .csv files containing many differently formatted tables. My end goal is to export each section individually into a its own .csv file. This is already working but I'm hoping to adjust the data, as described above, and then continue with exporting it to its own .csv file.

0 Avg Wind Speed       Gust Speed           Min Wind Speed     
1                 5.26                10.74                 1.34
2                 mi/h                 mi/h                 mi/h

Ideally, the output would look like this:

0 Avg Wind Speed (mi/h)       Gust Speed (mi/h)           Min Wind Speed (mi/h)     
1                 5.26                10.74                 1.34

Solution

  • df.columns=[c+"("+str(df.loc[2,c])+")" for c in df.columns]
    

    Renames all the columns by adding the value(converted to string) of the second row and respective column.

    df.loc[0,:]=[str(df.loc[0,c])+str(df.loc[2,c]) for c in df.columns ]
    

    This solution edits the first row not columns, not sure which one you want.