kynnemall
kynnemall

Reputation: 888

Pandas: how to add row values by index value

I'm having trouble working out how to add the index value of a pandas dataframe to each value at that index. For example, if I have a dataframe of zeroes, the row with index 1 should have a value of 1 for all columns. The row at index 2 should have values of 2 for each column, and so on.

Can someone enlighten me please?

Upvotes: 0

Views: 277

Answers (1)

jpp
jpp

Reputation: 164773

You can use pd.DataFrame.add with axis=0. Just remember, as below, to convert your index to a series first.

df = pd.DataFrame(np.random.randint(0, 10, (5, 5)))

print(df)

   0  1  2  3  4
0  3  4  2  2  2
1  9  6  1  8  0
2  2  9  0  5  3
3  3  1  1  7  0
4  2  6  3  6  6

df = df.add(df.index.to_series(), axis=0)

print(df)

    0   1  2   3   4
0   3   4  2   2   2
1  10   7  2   9   1
2   4  11  2   7   5
3   6   4  4  10   3
4   6  10  7  10  10

Upvotes: 1

Related Questions