gpt4 book ai didi

python - Pandas 有条件地创建数据框列 : based on multiple conditions

转载 作者:行者123 更新时间:2023-12-04 15:24:39 24 4
gpt4 key购买 nike

我有一个 df:

  col1 col2 col3
0 1 2 3
1 2 3 1
2 3 3 3
3 4 3 2
我想根据以下条件添加一个新列:
 - if   col1 > col2 > col3   ----->  2
- elif col1 > col2 -----> 1
- elif col1 < col2 < col3 -----> -2
- elif col1 < col2 -----> -1
- else -----> 0
它应该变成这样:
  col1 col2 col3   new
0 1 2 3 -2
1 2 3 1 -1
2 3 3 3 0
3 4 3 2 2
我遵循了 this post by unutbu 中的方法, 1 大于或小于 很好。但就我而言 多于 1 大于或小于 , 条件返回错误:
conditions = [
(df['col1'] > df['col2'] > df['col3']),
(df['col1'] > df['col2']),
(df['col1'] < df['col2'] < df['col3']),
(df['col1'] < df['col2'])]
choices = [2,1,-2,-1]
df['new'] = np.select(conditions, choices, default=0)


Traceback (most recent call last):

File "<ipython-input-43-768a4c0ecf9f>", line 2, in <module>
(df['col1'] > df['col2'] > df['col3']),

File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 1478, in __nonzero__
.format(self.__class__.__name__))

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我该怎么做?

最佳答案

将您的代码更改为

conditions = [
(df['col1'] > df['col2']) & (df['col2'] > df['col3']),
(df['col1'] > df['col2']),
(df['col1'] < df['col2']) & (df['col2'] < df['col3']),
(df['col1'] < df['col2'])]
choices = [2,1,-2,-1]
df['new'] = np.select(conditions, choices, default=0)

关于python - Pandas 有条件地创建数据框列 : based on multiple conditions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62526169/

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