【问题标题】:Do what np.select(condlist, choicelist) does but instead with pandas only做 np.select(condlist,choicelist) 做的事,但只用 pandas
【发布时间】:2020-07-20 08:12:06
【问题描述】:

我有代码,它工作正常:

import numpy as np
import pandas as pd


x = np.arange(10)
condlist = [x<3, x==5, x>5]
choicelist = [x, x**2, x**3]
a=np.select(condlist, choicelist)

现在让我们添加:

y=pd.Series(x)

现在让我们使用y 而不是x。现在我们需要得到与 pandas only 相同的结果(与 a 相同的内容,并且应该是 Series。),and 条件和选择应编码为上面(使用上面的代码进行编码条件和选择)。该怎么做?

【问题讨论】:

  • 预期输出应该与上面在a 中给出的代码完全相同。数据在y。
  • 你做过研究吗?
  • 这能回答你的问题吗? pandas equivalent of np.where
  • @AMC 我做过研究。这很有用,但它没有回答问题。下面的答案解决了这个问题。
  • 该问题的最佳答案与该问题的答案不是相同的解决方案吗?

标签: python pandas numpy


【解决方案1】:

从choicelist 构造一个数据框并将df.where 与condlist 一起使用

s = pd.DataFrame(choicelist).where(condlist).ffill().fillna(0).iloc[-1]

Out[99]:
0      0.0
1      1.0
2      2.0
3      0.0
4      0.0
5     25.0
6    216.0
7    343.0
8    512.0
9    729.0
Name: 2, dtype: float64

如果条件不重叠,也可以使用sum

s = pd.DataFrame(choicelist).where(condlist,0).sum()

Out[114]:
0      0
1      1
2      2
3      0
4      0
5     25
6    216
7    343
8    512
9    729
dtype: int64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2010-09-19
    • 2011-02-27
    相关资源
    最近更新 更多