我有来自多个来源的数据,其中包含有关如何将数据映射到分类值的规则。我不知道在熊猫中做到这一点的最佳方法。结合使用.eval
和.loc
,我可以制作一些相当复杂的表达式。
C
?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
答案 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]
,在True
为b
的情况下选择other_cond
,对于{{ 1}}。
True
中的条件可以相互包含,然后选择 first 满足,并且它是another_cond
condlist
中提到的条件都不为choicelist
时,选择 default_value
。