Skip to content Skip to sidebar Skip to footer

Python Enumeration/row Counter In A Pandas Column

Hello fellow stackoverflowers, New to the community with a Python (pandas/numpy) question. I'm using pandas and numpy to create a sample dataframe for testing. However, for severa

Solution 1:

N = 10

As a single step, you could use range:

sample_data = pd.DataFrame({       
        'A': np.random.rand(N), 
        'B' : range(1, N + 1)}
     )

print(sample_data)

          A   B
0  0.037303   1
1  0.693972   2
2  0.725926   3
3  0.110817   4
4  0.889411   5
5  0.138220   6
6  0.738190   7
7  0.695298   8
8  0.912171   9
9  0.601390  10

You can use enumerate as well, but you'll need to re-arrange the columns:

sample_data = pd.DataFrame(list(enumerate(np.random.rand(N), 1)),        
                     columns=['B', 'A'])[['A', 'B']]
print(sample_data)

          A   B
0  0.431247   1
1  0.004129   2
2  0.321802   3
3  0.866617   4
4  0.805049   5
5  0.767841   6
6  0.677050   7
7  0.293936   8
8  0.923059   9
9  0.953954  10

As an alternative, why not just use the index that the constructor automatically creates?

sample_data = pd.DataFrame({       
       'A': np.random.rand(N)})

sample_data['B'] = sample_data.index + 1
print(sample_data)

          A   B
0  0.117788   1
1  0.177268   2
2  0.762664   3
3  0.667486   4
4  0.531079   5
5  0.291939   6
6  0.066751   7
7  0.497935   8
8  0.883126   9
9  0.598048  10

Post a Comment for "Python Enumeration/row Counter In A Pandas Column"