假设给定日期框架df1,df2,df3,如果(df2> 0)否则以df3元素方式获取df = df1的最佳方法是什么?

最佳答案

您可以使用df.where实现此目的:

In [3]:
df1 = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df2 = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df3 = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))

print(df1)
print(df2)
print(df3)

          a         b         c
0 -0.378401  1.456254 -0.327311
1  0.491864 -0.757420 -0.014689
2  0.028873 -0.906428 -0.252586
3 -0.686849  1.515643  1.065322
4  0.570760 -0.857298 -0.152426

          a         b         c
0  1.273215  1.275937 -0.745570
1 -0.460257 -0.756481  1.043673
2  0.452731  1.071703 -0.454962
3  0.418926  1.395290 -1.365873
4 -0.661421  0.798266  0.384397

          a         b         c
0 -0.641351 -1.469222  0.160428
1  1.164031  1.781090 -1.218099
2  0.096094  0.821062  0.815384
3 -1.001950 -1.851345  0.772869
4 -1.137854  1.205580 -0.922832

In [4]:
df = df1.where(df2 >0, df3)
df

Out[4]:
          a         b         c
0 -0.378401  1.456254  0.160428
1  1.164031  1.781090 -0.014689
2  0.028873 -0.906428  0.815384
3 -0.686849  1.515643  0.772869
4 -1.137854 -0.857298 -0.152426

关于python - 数据帧上的元素级三元条件运算,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37214519/

10-12 16:47