多列条件选择

2024-09-30 10:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用pandas将下表作为Python中的数据帧加载

+--------+-------+------+
| Number | Col1  | Col2 |
+--------+-------+------+
| ABC    | TRUE  | SFG  |
| BCD    | TRUE  |      |
| CDE    | FALSE | SFG  |
| DEF    | FALSE |      |
| FEG    | TRUE  | JJI  |
+--------+-------+------+

数字,Col2-字符串;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中实现这个逻辑?你知道吗


Tags: andfalsetruenumberifisselectnull
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']

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

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

相关问题 更多 >

    热门问题