I have a question on pandas-python: Say I have a column with 1000 elements (integers), and its name is 'a' like
'a' = [2,2,2,2,2,2,2,2,2,2,2,2,..............]
I want to modify the elements by row index(every third number increase by 1 till the end of the column), and deleting the name. My final (and desired) output wold be:
'b' = [2,2,2,3,3,3,4,4,4,5,5,5..................]
Any hint?
CodePudding user response:
I'm not sure if this is the most efficient way of solving this, but the given code works:
import pandas as pd
alist = []
for i in range(0,1000):
alist.append(2)
data = {'a':alist}
dataset = pd.DataFrame(data)
count = 2
for i in range(0, (len(alist)//3), 3):
dataset.iloc[i: i 3 ] = count
count = count 1
I have looped through the dataframe a third of the total times while increasing the loop count by 3 and at every position used iloc to replace the value of the given column of the current row as well as the 2 after it with a variable count which was initialized from 2 and incremented at each step.
CodePudding user response:
a = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
c = []
for i in range(0, len(a), 3):
b = a[i : i 3]
for j in range(len(b)):
b[j] = b[j] (i // 3)
c.extend(b)
print(c)