简体   繁体   中英

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:

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? Thanks in advance!

If Index is an actual column you can use numpy.where and specify your condition

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM