熊猫数据条件映射最佳实践

时间:2020-10-21 07:28:06

标签: python pandas

我有来自多个来源的数据,其中包含有关如何将数据映射到分类值的规则。我不知道在熊猫中做到这一点的最佳方法。结合使用.eval.loc,我可以制作一些相当复杂的表达式。

  1. 是否可以在评估表达式中分配C
  2. 这是个坏主意吗?
df = pd.DataFrame({"A" : [1,2,3,4,5], "B" : [0, 1, 0, 1, 0], "Z" : [3, 2, 2, 1, 5]})
df["C"] = 0

x = df.eval("(A > 2) & (B == 0)")
df.loc[x, "C"] = 1

x = df.eval("(C == 0) & (B == 0) & (Z > 0)")
df.loc[x, "C"] = 2

df

    A   B   Z   C
0   1   0   3   2
1   2   1   2   0
2   3   0   2   1
3   4   1   1   0
4   5   0   5   1

1 个答案:

答案 0 :(得分:0)

如果您要使用 import std.variant; import std.stdio; class Callback { bool delegate(...) callback; Variant[] params; this(T)(T t) { this.callback = cast(bool delegate(...)) t; } this(T, A...)(T t, A a) { this.callback = cast(bool delegate(...)) t; foreach(item;a) { Variant temp = item; this.params ~= temp; } } void exec() { if(this.params.length) { writeln("Passed args: "); writeln(this.params); callback(this.params); } else { callback(); } } } void main() { bool test() { writeln("Executing first test"); return false; } bool test2(Variant[] params) { writeln("Received args: "); writeln(params); return false; } Callback cb = new Callback(&test); cb.exec(); writeln(); Callback cb2 = new Callback(&test2, "test2 executing", 1); cb2.exec(); } C:\Users\Nulrie\Documents\D>test Executing first test Passed args: [test2 executing, 1] Received args: [] C:\Users\Nulrie\Documents\D> 0作为输出,则使用将布尔掩码强制转换为1

int

您可以在此处使用np.where

#df['C'] = 0 is redundant in this case
df['C'] = (df.A.gt(2) & df.B.eq(0)).astype(int)
  • df['C'] = np.where(df.A.gt(2)&df.B.eq(0), 1, 0) 现在将np.where(cond, x, y)x替换为您认为合适的值。 y的值将在满足x的情况下使用,否则cond的值

如果您有多个与该条件相对应的条件输出,请使用np.select

y
    condlist = [df.A.gt(2)&df.B.eq(0), other_cond, another_cond] choicelist = ['a', 'b', 'c'] df['C'] = np.select(condlist, choicelist, default_value) a的情况下选择
  • condlist[0],在Trueb的情况下选择other_cond,对于{{ 1}}。

  • True中的条件可以相互包含,然后选择 first 满足,并且它是another_cond

    中的对应值
  • condlist中提到的条件都不为choicelist时,选择
  • default_value