我在使用熊猫的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中实现此逻辑?
发布于 2016-10-21 05:38:48
使用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']发布于 2016-10-20 21:46:29
下面是多个步骤的查询实现:
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: objecthttps://stackoverflow.com/questions/40164407
复制相似问题