Skip to content Skip to sidebar Skip to footer

Pandas Long To Wide Format With Multi-index

I have a dataframe that looks like this: data.head() Out[2]: Area Area Id Variable Name Variable Id Year \ 0 Argentina 9 Conservation agricultur

Solution 1:

I think you need first convert column Value to numeric and then use pivot_table with default aggregate function mean:

#if all float data saved as strings
data['Value'] = data['Value'].astype(float)
#if some bad data like strings and first method return value error
data['Value'] = pd.to_numeric(data['Value'], errors='coerce')

data.pivot_table(index=['Area', 'Year'], columns='Variable Name', values='Value')

Or:

data.groupby(['Area', 'Variable Name', 'Year'])[ 'Value'].mean().unstack('Variable Name')

Post a Comment for "Pandas Long To Wide Format With Multi-index"