简体   繁体   中英

how to add values to certain index in column in pandas dataframe (python)

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM