【问题标题】:How to compute series with different index?如何计算具有不同索引的序列?
【发布时间】:2018-01-08 17:31:07
【问题描述】:

比如我有两个系列

X = pd.Series([0,3,4,0,-1,0])
Y = pd.Series([4,2,5,1,3,5])

我想生成一个新系列 Z。

import pandas as pd
Z = []
for index in range(0,len(X)):
    if(X.iloc[index]!=0):
       temp = #(Do some arithmetic)
       Z.append(temp)
    elif(X.iloc[index]==0):
       temp = #(Do some arithmetic)
       Z.append(temp)

由于效率问题,可以不用For-Loop吗?

也许像:

Z = Y*Y [X != 0]
Z = Y*Y*Y [X == 0]
#I know this is wrong,but I dont know how to correct it

我不熟悉熊猫,请告诉我,tks!

【问题讨论】:

  • 你能显示你的预期输出吗?
  • 如果逻辑是(如果 X != 0 ,则 Z= YY),(如果 X==0 ,则 Z=YY*Y)然后 Z = [64,4,125,1,9,125] 就这样,确定 X 中的值,然后进行不同的计算。

标签: python-3.x pandas series


【解决方案1】:

IIUC 加或减 值都没有关系:

In [245]: (Y-X)/X.abs()
Out[245]:
0    3.000000
1   -0.333333
2    0.250000
3         inf
4    4.000000
5         NaN
dtype: float64

【讨论】:

  • @cᴏʟᴅsᴘᴇᴇᴅ,我也被 OP 的代码弄糊涂了... ;-)
  • 总之,我想先判断X的值是否为0,然后再做不同的操作。而且我不想用for循环一一确定X,也许Pandas可以做到?
  • @RickyParker,你可以使用“np.where()”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 2018-08-31
相关资源
最近更新 更多