Not sure if this is even possible, but i am trying to insert the header of my dataframe into a new row when the value in the 'Strategy' column changes.
Current Output:
Amount Code Strategy
1,000 Fund_1 A
2,000 Fund_2 A
3,000 Fund_1 B
4,000 Fund_2 B
5,000 Fund_1 C
6,000 Fund_2 C
Desired Output:
Amount Code Strategy
1,000 Fund_1 A
2,000 Fund_2 A
Amount Code Strategy
3,000 Fund_1 B
4,000 Fund_2 B
Amount Code Strategy
5,000 Fund_1 C
6,000 Fund_2 C
Is there an easy way to do this?
Here's one way you could achieve this effect using reindexing
and pandas.concat
:
d = {x:x for x in df.columns}
header_rows = df.drop_duplicates('Strategy').drop(0).assign(**d)
header_rows.index -= 0.5
df_new = pd.concat([df, header_rows]).sort_index().reset_index(drop=True)
print(df_new)
Amount Code Strategy
0 1,000 Fund_1 A
1 2,000 Fund_2 A
2 Amount Code Strategy
3 3,000 Fund_1 B
4 4,000 Fund_2 B
5 Amount Code Strategy
6 5,000 Fund_1 C
7 6,000 Fund_2 C
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.