我正在創建一個函式,該函式可以檢查資料集的多個條件,然后回傳兩個串列。
清單 1:執行 X 的專案
串列 2:執行 Y 的專案
樣本資料:
Product Variable Value
0 A Sell 0.1
1 B Keep -1.2
2 C Sell 0.3
3 D Swap 0.1
4 E Swap 0.1
理想結果:
Sell; A, C
Swap; 'Nothing to swap this week'
運行時報錯:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
到目前為止我的代碼:
def weekly_forcasting(df):
a = df['Swap or Sell']
b = df['Current Value']
if (a == 'Sell') and (b > 0).any():
return ('Product_Label')
if (a == 'Sell') and (b < 0).any():
return 'Nothing to sell this week'
if (a == 'Swap') and (b > 0).any():
return 'Nothing to swap this week'
if (a == 'Swap') and (b < 0).any():
return ('Product_Label')
uj5u.com熱心網友回復:
b = df['Current Value']b按照錯誤訊息的提示制作一個系列。所以理想情況下你想使用.loc,例如你可能想要
selling_list = (
df.loc[
(df["Swap or Sell"]=="Sell") & (df["Current Value"]>0)
]["Product_Label"].tolist() if
len(df.loc[
(df["Swap or Sell"]=="Sell") & (df["Current Value"]>0)
]["Product_Label"].tolist()) > 0
else "nothing to sell this week"
)
同樣你可以定義swapping_list并做一個return selling_list, swapping_list
uj5u.com熱心網友回復:
嘗試使用 numpy.select
import numpy as np
# create a list of condtions
conditions = [
(df['Swap or Sell'] == 'Sell') & (df['Current Value'] > 0),
(df['Swap or Sell'] == 'Sell') & (df['Current Value'] < 0),
(df['Swap or Sell'] == 'Swap') & (df['Current Value'] > 0),
(df['Swap or Sell'] == 'Swap') & (df['Current Value'] < 0),
]
# create a list of chices that mtach a statisifed condition
choices = [
df['Product_Label'],
'There are no Sell recommendations today',
'There are no Swap recommendations today',
df['Product_Label'],
]
# create a new by using numpy.select
df['data'] = np.select(conditions, choices, 'Keep')
然后只需使用布爾索引訪問您想要的資訊
df.loc[df['Swap or Sell'] == 'Sell', 'data']
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/384586.html
上一篇:制作這樣的數字表的簡單代碼
