0

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?

2
  • Can you provide an example of code you have tried so far with example data and the output you expect? Commented Jun 20, 2018 at 12:40
  • If you have a dataframe of zeroes and you try to multiply that by index value the dataframe will stay the same. Do you mean addition instead of multiplication? An example with expected output would help as stated above. Commented Jun 20, 2018 at 12:48

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

This seems like an addition while the question is asking for multiplication?
@MennoVanDijk, OP has now corrected the title to match the description.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.