[英]Create new column in Pandas DataFrame based on other columns
I have Dataframe like:我有像这样的数据框:
Now I would like to add column V based on conditions on I1, I2 and I3.现在我想根据 I1、I2 和 I3 的条件添加列 V。 Conditions are like:
条件是这样的:
v = 1 if I1>23 and I2.str.contains('abc')
v = 2 if I3 == 20
v == ...............
...................
One row can satisfy multiple condition what I want is to multiply such rows and filter out the rows which is not satisfying any condition such as suppose N1 will satisfy for V=1,2 and 3. While N2 does not satisfy any and N3 will satisfy v=2.一行可以满足多个条件我想要的是将这些行相乘并过滤掉不满足任何条件的行,例如假设 N1 将满足 V=1,2 和 3。而 N2 不满足任何条件,而 N3 将满足v=2。 I want the final dataframe to look like:
我希望最终的数据框看起来像:
Could someone please help me with this?有人可以帮我解决这个问题吗? Thanks.
谢谢。
If I understood your question correctly, suppose you have a dataframe like the below:如果我正确理解了您的问题,假设您有一个如下所示的数据框:
df = pd.DataFrame({
"NAME": [ "N1", "N2", "N3" ],
"I1": [ 1, 4, 4 ],
"I2": [ 2, 5, 2 ],
"I3": [ 3, 6, 6 ]
})
ie: IE:
>>> df
NAME I1 I2 I3
0 N1 1 2 3
1 N2 4 5 6
2 N3 4 2 6
To reproduce your example, I will assume that the conditions are I1 = 1
, I2 = 2
, and I3 = 3
:为了重现您的示例,我将假设条件为
I1 = 1
、 I2 = 2
和I3 = 3
:
cond1 = df["I1"] == 1
cond2 = df["I2"] == 2
cond3 = df["I3"] == 3
To build the expected dataframe, you can do:要构建预期的数据框,您可以执行以下操作:
result = pd.concat([
df[cond1].assign(V=1),
df[cond2].assign(V=2),
df[cond3].assign(V=3)
])
Result:结果:
>>> result
NAME I1 I2 I3 V
0 N1 1 2 3 1
0 N1 1 2 3 2
2 N3 4 2 6 2
0 N1 1 2 3 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.