I am fetching data from a source into a pandas data frame, it is like below
| date | currency | price |
|---|---|---|
| d1 | INR | 31 |
| d2 | INR | 32 |
| d2 | USD | 21 |
| d3 | USD | 41 |
| d3 | INR | 51 |
| d3 | JPY | 61 |
I want to convert it to below
| date | INR | JPY | USD |
|---|---|---|---|
| d1 | 31 | 0 | 0 |
| d2 | 32 | 0 | 21 |
| d3 | 51 | 61 | 42 |
I am fetching data from a source into a pandas data frame, it is like below
| date | currency | price |
|---|---|---|
| d1 | INR | 31 |
| d2 | INR | 32 |
| d2 | USD | 21 |
| d3 | USD | 41 |
| d3 | INR | 51 |
| d3 | JPY | 61 |
I want to convert it to below
| date | INR | JPY | USD |
|---|---|---|---|
| d1 | 31 | 0 | 0 |
| d2 | 32 | 0 | 21 |
| d3 | 51 | 61 | 42 |
You can use pivot to rotate your data around the currency column, then use fillna to replace NaN values with 0, and then finally reset_index and rename_axis to clean up the output:
df.pivot(index='date', columns='currency', values='price') \
.fillna(0) \
.reset_index() \
.rename_axis(None, axis=1)
Output:
date INR JPY USD
0 d1 31.0 0.0 0.0
1 d2 32.0 0.0 21.0
2 d3 51.0 61.0 41.0
Use pivot() to reshape the DataFrame, then transpose it with T.
df.pivot(index="currency", columns="data", values="price").T
Output:
currency INR JPY USD
data
d1 31.0 NaN NaN
d2 32.0 NaN 21.0
d3 51.0 61.0 41.0