0

I have a dataframe which looks like this:

enter image description here

I wanted to make a dataframe which looks like this:

enter image description here

For this I have referred the post at pandas convert some columns into rows.

By using the merge function I get a dataframe as shown below:

enter image description here

How do I get my dataframe in the format required?

The complete code is as shown:

import pandas as pd
from nsepy import get_history
from datetime import date
import numpy as np


stock = ['APLAPOLLO','AUBANK','AARTIDRUGS','AARTIIND','AAVAS','ABBOTINDIA','ADANIENT','ADANIGAS','ADANIGREEN','ADANIPORTS']
res = dict(zip(stock,stock))
start = date (2020, 11, 22)
end = date (2020, 12, 22)



for stock_name in stock:
    data = get_history(symbol=stock_name, start=start, end=end)
    res[stock_name]=data



for key, df in res.items():
   # create a column called "key name"
   df['key_name'] = key




lst = list(res.values())
df = pd.concat(lst)
df['boolean'] = df['Prev Close'] < df['Close']

df1 = pd.DataFrame({'boolean' : [True] + [False] * 2 + [True] * 3})
a = df['boolean']
b = a.cumsum()
df['trend'] = (b-b.mask(a).ffill().fillna(0).astype(int)).where(a, 0)

conditions = [(df['boolean']==True), (df['boolean']==False)]
values=['Win','Loose']
df['Win/Loss']=np.select(conditions,values)
df=df.drop(['Win/Loose'],axis=1)
df.to_csv('data.csv')
conditions = [(df['trend']>=2), df['trend']<2]
df2=df[['trend','Symbol']]
w=df2.melt(id_vars=["trend"],value_vars=['Symbol'])
Huzefa Sadikot
  • 561
  • 1
  • 7
  • 22

1 Answers1

3

IIUC, this can be solved with pivot_table():

Given the original dataframe you show in the first image:

new_df = df.pivot_table(index='Date',columns='Symbol',value='trend')
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53