简体   繁体   English

如何在 python 中执行以下操作

[英]how do I perform the below operation in python

Sorry probably av basic Q but struggling with it.抱歉,可能是基本的 Q,但正在努力解决。 I have nine variables Q1 through Q9 with initial values equal to zero.我有九个变量 Q1 到 Q9,初始值为零。

Q1 = Q2 = Q3 = Q4 = Q5 = Q6 = Q7 = Q8 = Q9 = 0

after certain operation I get new values assigned to some of the variables.在某些操作之后,我得到分配给某些变量的新值。

lets assume I assign values to some of the variables randomly as shown below
pd.DataFrame((np.arange(6)+1),index=['Q1','Q2','Q5','Q8','Q9','Q4'])

So variables 'Q3','Q6' and 'Q7' are unchanged.因此变量“Q3”、“Q6”和“Q7”保持不变。

Question is how do I get a final output in the form of a dataframe similar to shown below.问题是我如何以类似于如下所示的 dataframe 的形式获得最终的 output。 ie with new values where applicable else the original value ie 0即在适用的情况下使用新值,否则原始值即0

在此处输入图像描述

also, just to add any number of variables could have new values during the operation.此外,在操作期间添加任意数量的变量都可能具有新值。 ie in the above example 6 variables got new values, in some cases none might have new values or all 9 might have new values.即在上面的示例中,6 个变量获得了新值,在某些情况下,可能没有一个变量有新值,或者所有 9 个变量都可能有新值。

reindex

Docs 文档

Qs = [f'Q{i}' for i in range(1, 10)]
df.reindex(Qs, fill_value=0)

    0
Q1  1
Q2  2
Q3  0
Q4  6
Q5  3
Q6  0
Q7  0
Q8  4
Q9  5

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

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