簡體   English   中英

Python:根據其他兩個列的值有條件地創建新列

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

我想將兩列合並到一個新列中。

假設我有:

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

現在我想創建一個列 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

有 python 代碼嗎? 提前致謝!

如果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

如果您的索引是您的實際索引

您可以使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM