I have a dataframe (results) like this:
| index | results |
|---|---|
| 0 | 1 |
| 1 | -1 |
| 2 | 1 |
I have another dataframe (signals) like this:
| index | signals |
|---|---|
| 0 | 200 |
| 1 | 300 |
| 2 | 250 |
| 3 | 450 |
| 4 | 345 |
| 5 | 534 |
I want to add a column in signals such that the value from results will be copied twice in that column like
| index | signals | results |
|---|---|---|
| 0 | 200 | 1 |
| 1 | 300 | 1 |
| 2 | 250 | -1 |
| 3 | 450 | -1 |
| 4 | 345 | 1 |
| 5 | 534 | 1 |
Note: The 1 from index 0 from results is copied twice in index 0 and 1 of signals and so on. How can i go about doing this?
CodePudding user response:
IIUC, you just want to repeat results twice and assign it to a column in signals, right? In that case, you can use, np.repeat:
import numpy as np
signals['results'] = np.repeat(results['results'].to_numpy(), 2)
Output:
index signals results
0 0 200 1
1 1 300 1
2 2 250 -1
3 3 450 -1
4 4 345 1
5 5 534 1
CodePudding user response:
Keep it simple, just use the Series' repeat method:
n = len(signals) // len(results)
signals['results'] = result['results'].repeat(n).to_numpy()
output:
index signals results
0 0 200 1
1 1 300 1
2 2 250 -1
3 3 450 -1
4 4 345 1
5 5 534 1
CodePudding user response:
The @mozway's answer is more relevant than mine because he uses Series.repeat instead Index.repeat. The @Manlai's answer is interesting too.
Use Index.repeat:
n = len(signals) // len(results) # twice
signals['results'] = results.reindex(results.index.repeat(n)).to_numpy()
print(signals)
# Output
signals results
0 200 1
1 300 1
2 250 -1
3 450 -1
4 345 1
5 534 1
