pandasdataframecsvgroup-bypivot-table

Modifing a Pandas Dataframe using Pivot Tables or Group By


I'm trying to modify this pandas dataframe to output to a CSV file.

Original Dataframe

The output file will be used to upload data to another program so the file need to have specific headers for the data to be uploaded correctly.

This is the format needed for the CSV output file:

CSV Output Format

I've tried to modify the dataframe using pivot table and the following with no luck:

df2 = pd.get_dummies(SAMPDATA_w.set_index(['Sample ID', 'Sample Date', 'Result_F'])['ANALYTE']).groupby('Sample ID','ANALYTE').max().reset_index()

Any help would be appreciated.

Thanks


Solution

  • Is this the sort of thing you are looking for?

    df_pivot = df.pivot_table(index=['Sample ID', 'Sample Date', 'Unit Of Detection'],
                              columns='ANALYTE', values='Result_F', aggfunc='first').reset_index()
    
    print(df_pivot)
    
    

    Let me know if it works for you.