条件选择多列 - Python

时间:2016-10-20 20:57:42

标签: python pandas

我使用pandas

在Python中将下表作为数据框加载
+--------+-------+------+
| Number | Col1  | Col2 |
+--------+-------+------+
| ABC    | TRUE  | SFG  |
| BCD    | TRUE  |      |
| CDE    | FALSE | SFG  |
| DEF    | FALSE |      |
| FEG    | TRUE  | JJI  |
+--------+-------+------+

Number,Col2 - String; Col1 - 布尔值

我想使用以下逻辑

从此df中选择行
IF Col1 = TRUE and Col2 is not null Select Number + "," + Col2
ELSE IF Col1 = TRUE and Col2 is null Select Number
ELSE IF Col2 is not null and Col1 = FALSE Select Col2

在上述情况下,输出应为具有以下值的列表

["ABC", "SFG", "BCD", "FEG", "JJI"] //Removing the repetition too ("SFG")

如何使用Pandas在Python中实现此逻辑?

2 个答案:

答案 0 :(得分:2)

以下是多个步骤的查询实现:

import pandas as pd
df = pd.DataFrame(data={'Number': ['ABC', 'BCD', 'CDE', 'DEF', 'FEG'],
                        'Col1': [True, True, False, False, True],
                        'Col2': ['SFG', None, 'SFG', None, 'JJI']})
cond1 = df.Col1 & ~df.Col2.isnull()
cond2 = df.Col1 & df.Col2.isnull()
cond3 = ~df.Col1 & ~df.Col2.isnull()
selects = [df[cond1].Number + ',' + df[cond1].Col2, 
           df[cond2].Number, 
           df[cond3].Col2]
result = pd.concat(selects).sort_index()

result(与@MaxU预测相同)

0    ABC,SFG
1        BCD
2        SFG
4    FEG,JJI
dtype: object

答案 1 :(得分:2)

使用where + stack + tolist

pd.concat([df.Number.where(df.Col1, np.nan), df.Col2], axis=1).stack().tolist()

['ABC', 'SFG', 'BCD', 'SFG', 'FEG', 'JJI']

获取唯一列表

pd.concat([df.Number[df.Col1], df.Col2.dropna()]).unique().tolist()

['ABC', 'BCD', 'FEG', 'SFG', 'JJI']