Home > Software design >  Creating a stack list in pandas
Creating a stack list in pandas

Time:03-16

I am trying to create a column called days for 27 different cities with 151 rows for each city so a total of 4077 rows. 0 to 151 represent no of days for each cities. I have the following code. is there way of creating 4077 rows without doing it 27 times and appending the columns.

city1=pd.Series(range(0,151),name="days")
city1.to_frame()
days
0   0
1   1
2   2
3   3
4   4
... ...
146 146
147 147
148 148
149 149
150 150
151 rows × 1 columns

CodePudding user response:

IIUC, one way using pandas.MultiIndex.from_product:

s = pd.MultiIndex.from_product([range(27), range(151)])
df = s.to_frame(False, ["cities", "days"])
print(df)

Output:

      cities  days
0          0     0
1          0     1
2          0     2
3          0     3
4          0     4
...      ...   ...
4072      26   146
4073      26   147
4074      26   148
4075      26   149
4076      26   150

CodePudding user response:

Please try this:

import numpy as np
import pandas as pd
no_city =27
no_days = 151
days = list(range(0,no_days)) * no_city
city_names = ['city_' str(i 1) for i in range(0,no_city)] #provide city list if you already have
city_names = np.repeat(city_names,no_days)
df = pd.DataFrame({'city':city_names,'days':days})
  • Related