Reputation: 23
I am newborn in python. Kindly help me in the following query:-
There are 8760 records(rows) in my dataframe (df) such that
Temperature
5
10
8
3
1
.
.
.
I want to assign specific range value (either 1 to 7 or 1 to 365) to new column and then repeat this range up to last records in the same column. The expected result is to be like this:
DayNumber
1
2
3
4
5
6
7
1
2
3
4
5
6
7
1
2
3
.
.
.
How do I achieve this kind of output?
Upvotes: 1
Views: 842
Reputation: 75080
Simplest method:
You can make a list of 1-7 by :
a = list(np.arange(7)+1)
Then use:
from itertools import cycle, islice
df['DayNumber'] = list(islice(cycle(a), len(df)))
This will allow you to cycle your list for n number of times here which is the length of your dataframe.
Time taken for 365 entries:
%timeit list(islice(cycle(a), len(df)))
#6.26 µs ± 78.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Upvotes: 0
Reputation: 1475
This seems easier
df = pd.DataFrame([range(10)]).T
df.columns = ["Temperature"]
df
Temperature
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
n=7
ll = pd.DataFrame(range(1, n+1)*(len(df)/n +1))
ll
0
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 1
8 2
9 3
10 4
11 5
12 6
13 7
df.join(ll)
Temperature 0
0 0 1
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6
6 6 7
7 7 1
8 8 2
9 9 3
Upvotes: 0
Reputation: 630
My method is easier for you to understand. Since I do not have the data, I assume the temperature is always 10 degrees Celsius. You can change it with yours.
import pandas as pd
temperature = [10] * 8760
days = []
row = 1
day = 1
while row <= 8760:
days.append(day)
day += 1
row += 1
if day == 8:
day = 1
data = {"temperature": temperature, "day": days}
df = pd.DataFrame(data=data)
Upvotes: 1