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
00.037303110.693972220.725926330.110817440.889411550.138220660.738190770.695298880.912171990.60139010
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
00.431247110.004129220.321802330.866617440.805049550.767841660.677050770.293936880.923059990.95395410
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 + 1print(sample_data)
A B
00.117788110.177268220.762664330.667486440.531079550.291939660.066751770.497935880.883126990.59804810
Post a Comment for "Python Enumeration/row Counter In A Pandas Column"