0

I have dataframes first and second of the same length, where the first one's index is increments of 15 and the second is in increments of 1. I would like to assign one column of first to another of second.

e.g., something like below

import pandas as pd

first = pd.DataFrame({"index": [0, 15, 30], "value": [2.2, 2.2, 2.2]})
second = pd.DataFrame({"value": [3.2, 3.2, 3.2]})
first = first.set_index("index")
first.value = second.value

however, the indices are disparate so the above gives NaNs for first.value after the first row. I think one approach is to call reset_index() prior to assignment, but I believe this is a costly op? Is there an approach that doesn't involve resetting the index?

1 Answer 1

2

IIUC, you can assign numpy array to dataframe column

first['value'] = second['value'].values
# or
first['value'] = second['value'].to_numpy()
print(first)

       value
index
0        3.2
15       3.2
30       3.2
Sign up to request clarification or add additional context in comments.

2 Comments

ah I see, but is calling values or to_numpy() more costly than reset_index()?
@roulette01 It won't, values wipes index from Series while reset_index() involves index and column conversion.

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.