简体   繁体   English

如何将值添加到 pandas dataframe 中的列中的某个索引(python)

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

I have a dataframe (results) like this:我有一个像这样的 dataframe (结果):

index指数 results结果
0 0 1 1
1 1 -1 -1
2 2 1 1

I have another dataframe (signals) like this:我有另一个 dataframe (信号)是这样的:

index指数 signals信号
0 0 200 200
1 1 300 300
2 2 250 250
3 3 450 450
4 4 345 345
5 5 534 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 0 200 200 1 1
1 1 300 300 1 1
2 2 250 250 -1 -1
3 3 450 450 -1 -1
4 4 345 345 1 1
5 5 534 534 1 1

Note: The 1 from index 0 from results is copied twice in index 0 and 1 of signals and so on.注意:结果中索引 0 的 1 在信号的索引 0 和 1 中复制两次,依此类推。 How can i go about doing this?我该怎么做 go?

IIUC, you just want to repeat results twice and assign it to a column in signals , right? IIUC,您只想重复两次results并将其分配给signals中的一列,对吗? In that case, you can use, np.repeat :在这种情况下,您可以使用np.repeat

import numpy as np
signals['results'] = np.repeat(results['results'].to_numpy(), 2)

Output: 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 . @mozway 的答案比我的更相关,因为他使用Series.repeat而不是Index.repeat The @Manlai's answer is interesting too. @Manlai 的回答也很有趣。

Use Index.repeat :使用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:保持简单,只需使用 Series 的repeat方法:

n = len(signals) // len(results)
signals['results'] = result['results'].repeat(n).to_numpy()

output: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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