DmitrySemenov
DmitrySemenov

Reputation: 10315

Apply a PeriodIndex of a single value to all rows of pandas dataframe

Let's say we have the following initial dataframe

branch_id    location                  employee

1            City, US    ...           26
2            City, US    ...           14
3            City, UK    ...           28

It has no index, I need to move all records of that dataframe into index (PeriodIndex) consisting just of a single value.

                      branch_id     location                  employee
date                           
2018-10-22/2018-10-28 1             City, US    ...           26
                      2             City, US    ...           14
                      3             City, UK    ...           28

How to achieve it with pandas?

Upvotes: 0

Views: 70

Answers (1)

Mayank Porwal
Mayank Porwal

Reputation: 34056

You can create a dummy column date with the same value(2018-10-22/2018-10-28 from your example) in the dataframe like this:

df['date'] = '2018-10-22/2018-10-28'

Then, you can use set_index to make this column as the dataframe's index:

df = df.set_index('date')

Consider the dataframe below:

In [80]: df
Out[80]: 

 A  B  C  D  E
 2  6  5  4  1
 1  2  8  4  9
 3  4  2  9  3

Added a dummy column date to it:

In [84]: df['date'] = '2018-10-22/2018-10-28'
In [85]: df
Out[85]: 
   A  B  C  D  E                   date
0  2  6  5  4  1  2018-10-22/2018-10-28
3  1  2  8  4  9  2018-10-22/2018-10-28
6  3  4  2  9  3  2018-10-22/2018-10-28

Now, setting date as index of the dataframe:

In [87]: df = df.set_index('date')

In [88]: df
Out[88]: 
                       A  B  C  D  E
date                                
2018-10-22/2018-10-28  2  6  5  4  1
2018-10-22/2018-10-28  1  2  8  4  9
2018-10-22/2018-10-28  3  4  2  9  3

Now, all rows have the same index. Let me know if this helps.

Upvotes: 1

Related Questions