Pandas Dataframe-不使用循环更新动态行和列
我有一个源数据帧Pandas Dataframe-不使用循环更新动态行和列,pandas,numpy,dataframe,Pandas,Numpy,Dataframe,我有一个源数据帧 source.head() Out[41]: A B C compare 892 4.031250 6.218750 6.515625 4.246094 893 4.079531 6.222656 5.945312 4.038281 894 4.023438 6.226562 6.039062 4.250000 895 5.109531 4.238281 6.035156 4.0382
source.head()
Out[41]:
A B C compare
892 4.031250 6.218750 6.515625 4.246094
893 4.079531 6.222656 5.945312 4.038281
894 4.023438 6.226562 6.039062 4.250000
895 5.109531 4.238281 6.035156 4.038281
896 4.019531 6.242188 6.089844 4.242188
以及具有相同索引的目标数据帧
target.tail()
Out[42]:
A B C
636893 0 0 0
636894 0 0 0
636895 0 0 0
636896 0 0 0
636897 0 0 0
我想这样做-
a. index where 'compare' is less than min of the rest.
b. the column of the min of the rest
target.head()
Out[41]:
A B C
892 0 0 0
893 4.038281/4.079531 0 0
894 0 0 0
895 0 4.038281/4.238281 0
896 0 0 0
我知道。i、 e.通过以下方式选择指数,其中比较小于剩余值的最小值:
tenors = ['A', 'B', 'C']
idx_select= source.index[(source['compare'] < source[tenors].min(1))]
我不知道如何进行第二步,即更新目标值,除了按行循环
有什么避免循环的建议吗?您可以尝试以下方法,希望能自我解释:
cols = ['A','B','C']
target = df[cols].div(df.compare, axis='rows')
target = target.where(target.gt(1) & target.eq(target.min(1), axis='rows'), 0)
输出:
打印(目标)
cols = ['A','B','C']
target = df[cols].div(df.compare, axis='rows')
target = target.where(target.gt(1) & target.eq(target.min(1), axis='rows'), 0)
A B C
892 0.000000 0.000000 0.0
893 1.010215 0.000000 0.0
894 0.000000 0.000000 0.0
895 0.000000 1.049526 0.0
896 0.000000 0.000000 0.0