我的目標是根據將其他列的值考慮在內的條件向資料框中添加一列。
我創建了一個生成相同錯誤的簡單示例:
numbers = {'A': [1,2,3,4,5], "B":[2,4,3,3,2]}
df = pd.DataFrame(numbers)
if df.A - df.B > 0:
df["C"] = df.B*5
else: df["C"] = 0
ValueError:Series 的真值不明確。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
我確信解決方案很簡單,但我是初學者。感謝您的支持。
uj5u.com熱心網友回復:
c = []
for lab, row in df.iterrows():
curr = 0
if row['A'] > row['B']:
curr = row['B'] * 5
c.append(curr)
df['C'] = c
uj5u.com熱心網友回復:
#Import pandas module
import pandas as pd
#Lists of data
list_A = [1,2,3,4,5]
list_B = [2,4,3,3,2]
#Define a dictionary containing lists of data
dictionary = {'A': list_A,
'B': list_B}
#Convert the dictionary into DataFrame
data = pd.DataFrame(dictionary)
data
#New list
data_diff = data.A - data.B
new_list=[]
for i in data_diff:
if i > 0:
new_list.append(i*5)
else:
new_list.append(0)
#New dataframe
new_dictionary = {'A': [1,2,3,4,5],
'B': [2,4,3,3,2],
'C': new_list}
new_data=pd.DataFrame(new_dictionary)
new_data
幾點說明:這是我非常簡單的版本。當然,還有許多其他更智能、更“pythonic”的版本。最后,我認為這個教程網站可以幫助你。
uj5u.com熱心網友回復:
你可以這樣做:
df["C"] = df.A - df.B
# First turns negative values into 0s
df["C"].mask(df["C"] <= 0, 0, inplace=True)
# Then divides everything by 2. The 0s will still remain 0.
df["C"] = df["C"] * 0.5
uj5u.com熱心網友回復:
您可以使用 numpy 的where:
df["C"] = np.where(df["A"] > df["B"], df["B"]*5, 0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/457946.html
