Reputation: 101
I am trying to reshape dataframe as shown in the images. I want to create a wide dataframe with the values in asset as new columns with the prefix asset_. In the new asset_ columns the corresponding value from the value column should be stored. See attached images. This is some sort of pivot operation but I can't figure out following:
I tried to do this with pandas.pivot but there are no prefix parameter and I do not want to create any multilevel indexes:
Import pandas as pd
data = {"rowkey":["2017:P7W", "2017:P7W", "2017:P7W"],
"ser_num":[467, 467, 467],
"asset": ["A", "B", "C"],
"value": [123,456, 789],
"day":[1,1,1]}
df = pd.DataFrame(data)
df.pivot(index="rowkey", columns="asset", values="value").reset_index()
In my problem I have 200+ unique assets so the result will be a very wide dataframe. See images:
Upvotes: 9
Views: 10591
Reputation: 301
You can use the add_prefix()
method as shown below:
# Create pandas dataframe
import pandas as pd
data = {
"rowkey": ["2017:P7W", "2017:P7W", "2017:P7W"],
"ser_num": [467, 467, 467], "asset": ["A", "B", "C"],
"value": [123,456,789],"day":[1,1,1]
}
df = pd.DataFrame(data)
# Pivot data and add prefix
df.pivot(index="rowkey",columns="asset",values="value").reset_index().add_prefix('asset_')
here an output after manipulation:
Best,
Abakar
Upvotes: 10