1

I have a Time-Series Data Frame in the below sample:

Date         Ticker      Price
2018-01-01    AAA        100
2018-01-01    BBB        200
2018-01-01    CCC        1000
2018-01-01    DDD        3000
2018-01-02    BBB        201
2018-01-02    CCC        1001

I want to obtain Unique values of "Ticker" column and convert the unique tickers into the dataframe columns. My data frame is supposed to look like the below

Date          AAA      BBB    CCC    DDD
2018-01-01    100      200    1000   3000
2018-01-02    NaN      201    1001   NaN

I am a bit new to Python, and yet to find a way to get around it. Could anyone suggest an efficient solution because I am dealing about 1M such rows at a time and need a solution that works faster was well. Thanx in adv.

RC0706
  • 25
  • 5

1 Answers1

1

You can use pivot_table:

df = pd.pivot_table(df, values = 'Price', index='Date', columns = 'Ticker').reset_index().rename_axis(None, axis=1)

Dataframe:

         Date Ticker  Price
0  2018-01-01    AAA    100
1  2018-01-01    BBB    200
2  2018-01-01    CCC   1000
3  2018-01-01    DDD   3000
4  2018-01-02    BBB    201
5  2018-01-02    CCC   1001

Output:

              Date    AAA    BBB     CCC     DDD
0       2018-01-01  100.0  200.0  1000.0  3000.0
1       2018-01-02    NaN  201.0  1001.0     NaN
Joe
  • 12,057
  • 5
  • 39
  • 55