gpt4 book ai didi

python - 根据其他列的值将新列添加到数据框

转载 作者:行者123 更新时间:2023-12-01 01:17:03 24 4
gpt4 key购买 nike

我读过很多有关此问题的问题,但我不知道如何将这些解决方案应用于我自己的问题。我想我必须使用 df.applydf.assign 但即使在阅读文档后我也不明白

这是我的数据:

d = {'switchopen': [True, True, False, False, False, False, False, False, False, False, False, False, False, True, True, False, False, True ],
'switchclose': [ False, False, False, False, False, True, True, True, True, True, False, False, False, False, False, False, False, False]}

df = pd.DataFrame(data=d)

switchopen == True & switchclose == False

时打开

switchopen == False & switchclose == True时关闭

switchopen == False & switchclose == False 时它会移动

我当前的解决方案是这样的:

dfopen = df[(df.switchclose == False) & (df.switchopen == True)]
dfopen['Open'] = 'open'
dfclose = df[(df.switchclose == True) & (df.switchopen == False)]
dfclose['Moving'] = 'close'
dfmoving = df[(df.switchclose == False) & (df.switchopen == False)]
dfmoving['Close'] = 'moving'

dfs = [dfopen, dfclose, dfmoving]
dfz = pd.concat(dfs, sort= False)
dfz = dfz.sort_index(ascending=True)

dfz['Position'] = dfz['Position'].fillna(dfz['Open'])
dfz['Position'] = dfz['Position'].fillna(dfz['Close'])
print(dfz['Position'])

这给了我我想要的东西,但我正在寻找更好的解决方案,例如:

df['Close'] = (df.switchclose == True & df.switchopen == False)
df['Open'] = (df.switchclose == False & df.switchopen == False)
df['Moving'] = (df.switchclose == False & df.switchopen == False)

然后使用.fillna

如果有一个解决方案甚至不需要该步骤,那就最好了

预期输出是这样的:

       Position
0 open
1 open
2 moving
3 moving
4 moving
5 close
6 close
7 close
8 close
9 close
10 moving
11 moving
12 moving
13 open
14 open
15 moving
16 moving
17 open

最佳答案

考虑到您的逻辑要求和输出期望,这应该可行

df.loc[(df['switchopen'] == True) & (df['switchclose'] == False), 'Position'] = 'open'
df.loc[(df['switchopen'] == False) & (df['switchclose'] == True), 'Position'] = 'closed'
df.loc[(df['switchopen'] == False) & (df['switchclose'] == False), 'Position'] = 'moving'

关于python - 根据其他列的值将新列添加到数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54234223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com