简体   繁体   English

Python:根据其他两个列的值有条件地创建新列

[英]Python: create new column conditionally on values from two other columns

I would like to combine two columns in a new column.我想将两列合并到一个新列中。

Lets suppose I have:假设我有:

Index A B
0     1 0
1     1 0
2     1 0
3     1 0
4     1 0
5     1 2
6     1 2
7     1 2
8     1 2
9     1 2
10    1 2

Now I would like to create a column C with the entries from A from Index 0 to 4 and from column B from Index 5 to 10. It should look like this:现在我想创建一个列 C,其中包含 A 中索引 0 到 4 的条目以及 B 列中索引 5 到 10 中的条目。它应该如下所示:

Index A B C
0     1 0 1
1     1 0 1
2     1 0 1
3     1 0 1
4     1 0 1
5     1 2 2
6     1 2 2
7     1 2 2
8     1 2 2
9     1 2 2
10    1 2 2

Is there a python code how I can get this?有 python 代码吗? Thanks in advance!提前致谢!

If Index is an actual column you can use numpy.where and specify your condition如果Index是实际列,您可以使用numpy.where并指定您的条件

import numpy as np

df['C'] = np.where(df['Index'] <= 4, df['A'], df['B'])

    Index  A  B  C
0       0  1  0  1
1       1  1  0  1
2       2  1  0  1
3       3  1  0  1
4       4  1  0  1
5       5  1  2  2
6       6  1  2  2
7       7  1  2  2
8       8  1  2  2
9       9  1  2  2
10     10  1  2  2

if your index is your actual index如果您的索引是您的实际索引

you can slice your indices with iloc and create your column with concat.您可以使用 iloc 对索引进行切片,并使用 concat 创建列。

df['C']  = pd.concat([df['A'].iloc[:5], df['B'].iloc[5:]])


print(df)

    A  B  C
0   1  0  1
1   1  0  1
2   1  0  1
3   1  0  1
4   1  0  1
5   1  2  2
6   1  2  2
7   1  2  2
8   1  2  2
9   1  2  2
10  1  2  2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python数据框:创建新列,该列有条件地连接1或3个其他列中的字符串值 - Python Data frame: Create New Column that Conditionally Concatenates String Values from 1 or 3 Other Columns 如何通过比较其他两个列来创建具有值的新列? - How to create a new column with values from comparing two other columns? 根据其他两列的值,在 pandas 中创建一个新列 - Create a new column in pandas depending on values from two other columns 从其他 df 列有条件地创建新列 - Create new column conditionally from other df columns Pandas/Python:如何根据其他列的值创建新列并将额外条件应用于此新列 - Pandas/Python: How to create new column based on values from other columns and apply extra condition to this new column 如何根据来自其他两列的值的分组总和创建新的值列? - How can I create a new column of values based on the grouped sum of values from two other columns? 如何通过引用其他两列在 Python Dataframe 中创建新列? - How to create a new column in Python Dataframe by referencing two other columns? 根据来自其他两列的条件文本值在 Pandas 中创建一个新列 - Create a new column in pandas based on conditional text values from two other columns pandas,根据其他两列的值创建一个新的唯一标识符列 - pandas, create a new unique identifier column based on values from two other columns 如何使用 Python 中的其他列值创建新列? - How to Create new columns using other column Values in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM