PhysicalChemist
PhysicalChemist

Reputation: 560

Pandas new column with constant increments

I need a new column that adds in increments, in this case .02.

DF before:

           x         y        x2        y2
0   1.022467  1.817298  1.045440  3.302572
1   1.026426  1.821669  1.053549  3.318476
2   1.018198  1.818419  1.036728  3.306648
3   1.013077  1.813290  1.026325  3.288020
4   1.017878  1.811058  1.036076  3.279930

DF after:

           x         y        x2        y2         t
0   1.022467  1.817298  1.045440  3.302572  0.000000
1   1.026426  1.821669  1.053549  3.318476  0.020000
2   1.018198  1.818419  1.036728  3.306648  0.040000
3   1.013077  1.813290  1.026325  3.288020  0.060000
4   1.017878  1.811058  1.036076  3.279930  0.080000
5   1.016983  1.814031  1.034254  3.290708  0.100000

I have looked around for a while, and cannot find a good solution. The only way on my mind is to make a standard python list and bring it in. There has to be a better way. Thanks

Upvotes: 2

Views: 797

Answers (1)

Alexander
Alexander

Reputation: 109576

Because your index is the perfect range for this (i.e. 0...n), just multiply it by your constant:

df['t'] = .02 * df.index.values

>>> df
          x         y        x2        y2     t
0  1.022467  1.817298  1.045440  3.302572  0.00
1  1.026426  1.821669  1.053549  3.318476  0.02
2  1.018198  1.818419  1.036728  3.306648  0.04
3  1.013077  1.813290  1.026325  3.288020  0.06
4  1.017878  1.811058  1.036076  3.279930  0.08

You could also use a list comprehension:

df['t'] = [0.02 * i for i in range(len(df))]

Upvotes: 2

Related Questions