简体   繁体   English

基于其他列在 Pandas DataFrame 中创建新列

[英]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 = 1I2 = 2I3 = 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.

相关问题 根据其他列中的“NaN”值在 Pandas Dataframe 中创建一个新列 - Create a new column in Pandas Dataframe based on the 'NaN' values in other columns Pandas数据框基于其他数据框的列创建新列 - Pandas dataframe create a new column based on columns of other dataframes Pandas DataFrame 基于其他两列创建新的 csv 列 - Pandas DataFrame create new csv column based on two other columns 基于数据框的其他列创建一个新的熊猫数据框列 - Create a new pandas dataframe column based on other column of the dataframe Pandas:根据 DataFrame 中的其他列在 DataFrame 中创建新列 - Pandas: Create new column in DataFrame based on other column in DataFrame pandas Dataframe:根据其他列创建新的标签列 - pandas Dataframe: create new columns of labels based on other columns 如何从数据框中的其他列创建新的Pandas数据框列 - How to create a new Pandas dataframe column from other columns in the dataframe 如何根据 Pandas DataFrame 中其他列的值创建新列 - How to create a new column based on values from other columns in a Pandas DataFrame 根据其他列行中的过滤值在 pandas dataframe 中创建一个新列 - Create a new Column in pandas dataframe based on the filetered values in the row of other columns 如何根据 pandas dataframe 中其他列中的子字符串创建新列? - How to create new column based on substrings in other column in a pandas dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM