多列条件选择-Python
我使用pandas将下表作为Python中的数据帧加载多列条件选择-Python,python,pandas,Python,Pandas,我使用pandas将下表作为Python中的数据帧加载 +--------+-------+------+ | Number | Col1 | Col2 | +--------+-------+------+ | ABC | TRUE | SFG | | BCD | TRUE | | | CDE | FALSE | SFG | | DEF | FALSE | | | FEG | TRUE | JJI | +--------+----
+--------+-------+------+
| 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中实现此逻辑?以下是查询的多个步骤实现:
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()
结果
为(与@MaxU预测值相同)
使用
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']
嗯,我得到了
['ABC,SFG','BCD','SFG',nan',FEG,JJI']
按照您的逻辑,您可能需要使用嵌套的numpy.where
语句。
pd.concat([df.Number[df.Col1], df.Col2.dropna()]).unique().tolist()
['ABC', 'BCD', 'FEG', 'SFG', 'JJI']