Pandas 真假匹配
对于此表: 我想生成“所需的_输出”列。实现这一目标的一种方法可能是:Pandas 真假匹配,pandas,dataframe,boolean,calculated-columns,Pandas,Dataframe,Boolean,Calculated Columns,对于此表: 我想生成“所需的_输出”列。实现这一目标的一种方法可能是: col_1的所有真值直接传输到所需的_输出(红色箭头) 在所需的_输出中,将真值置于任何现有真值之上(绿色箭头) 我尝试过的代码: df['desired_output']=df.col_1.apply(lambda x: True if x.shift()==True else False) 谢谢您可以通过|对按位或原始值进行链接,并通过以下方式移动值: 试试这个 df['desired_output'] = df['
df['desired_output']=df.col_1.apply(lambda x: True if x.shift()==True else False)
谢谢您可以通过
|
对按位或
原始值进行链接,并通过以下方式移动值:
试试这个
df['desired_output'] = df['col_1']
df.loc[1:, 'desired_output'] = df.col_1[1:].values | df.col_1[:-1].values
print(df)
以防这些被保存为字符串。所有大写字母(真/假) 输入: 代码: 输出:
col_1 desired
0 True True
1 True True
2 False True
3 True True
4 True True
5 False False
6 Flase True
7 True True
8 False False
@AngusStevenson如果值保存为字符串,我的答案将特别有效。“真”(与你在问题中的形象相似),而不是“真”。
col_1
0 True
1 True
2 False
3 True
4 True
5 False
6 Flase
7 True
8 False
df['desired']=df['col_1']
for i, e in enumerate(df['col_1']):
if e=='True':
df.at[i-1,'desired']=df.at[i,'col_1']
df = df[:(len(df)-1)]
df
col_1 desired
0 True True
1 True True
2 False True
3 True True
4 True True
5 False False
6 Flase True
7 True True
8 False False