[英]how to add values to certain index in column in pandas dataframe (python)
I have a dataframe (results) like this:我有一个像这样的 dataframe (结果):
index![]() |
results![]() |
---|---|
0 ![]() |
1 ![]() |
1 ![]() |
-1 ![]() |
2 ![]() |
1 ![]() |
I have another dataframe (signals) like this:我有另一个 dataframe (信号)是这样的:
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.注意:结果中索引 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.