[英]How to return True/False instead of 1/0 in python
我試圖在一個循環中評估兩個浮點值,由於某種原因,評估返回 1/0 而不是 True/False。
def new_row(item1, item2):
new_row = {
'lister': item1,
'metric': item2
}
return new_row
final_df = pd.DataFrame()
lister = ['a', 'b', 'c']
position = [1.1, 2.3, 4.5]
evaluation_metric = [0, 0.5, 0.2]
for b1 in lister:
print(abs(position) > evaluation_metric)
metric = (abs(position) > evaluation_metric)
nr = new_row(lister, metric)
final_df = final_df.append(nr, ignore_index=True)
出於某種原因,當我打印時我得到 True 但是當我 append 它到最終的df
時我得到 1.0。 關於如何在final_df
而不是 1.0 中獲得 True 的任何想法?
您創建了一個沒有列的 dataframe,因此 pandas 必須猜測添加一行時要做什么。 在類似的實驗中,它選擇了float64
:
>>> import pandas as pd
>>> df = pd.DataFrame()
>>> final = df.append({"lister":"a", "metric":False}, ignore_index=True)
>>> final
lister metric
0 a 0.0
>>> final.dtypes
lister object
metric float64
dtype: object
完成附加后,您可以修復 dtype
>>> final["metric"] = final["metric"].astype(bool)
>>> final
lister metric
0 a False
但是您可能不應該首先附加。 pandas
允許您對整個列執行操作。 首先從列表中創建列,然后一步完成操作,如
import pandas as pd
lister = ['a', 'b', 'c']
position = [1.1, 2.3, 4.5]
evaluation_metric = [0, 0.5, 0.2]
df = pd.DataFrame({"lister":lister, "position":position,
"evaluation_metric":evaluation_metric})
df["metric"] = df["position"] > df["evaluation_metric"]
print(df)
Output
lister position evaluation_metric metric
0 a 1.1 0.0 True
1 b 2.3 0.5 True
2 c 4.5 0.2 True
如果您不再需要這些其他列,則可以刪除它們
df.drop(["position", "evaluation_metric"], axis=1, inplace=True)
盡管您發布的代碼不會運行(建議您解決此問題,因此您的問題不會關閉),但問題是將bool
類型的行附加到空 DataFrame 將導致轉換為float64
(根據這個答案):
例如:
for l,p,e in zip(lister,position,evaluation_metric):
metric = (abs(p) > e)
nr = new_row(l, metric)
final_df = final_df.append(nr, ignore_index=True)
>>> final_df.dtypes
lister object
metric float64
您可以通過修改new_row
function 以返回 DataFrame 來解決此問題,然后在每次循環迭代中將其連接到 final_df:
def new_row(item1, item2):
new_row = {
'lister': [item1],
'metric': [item2]
}
return pd.DataFrame(new_row)
final_df = pd.DataFrame()
lister = ['a', 'b', 'c']
position = [1.1, 2.3, 4.5]
evaluation_metric = [0, 0.5, 0.2]
for l,p,e in zip(lister,position,evaluation_metric):
metric = (abs(p) > e)
nr = new_row(l, metric)
final_df = pd.concat([final_df,nr])
Output:
>>> final_df
lister metric
0 a True
0 b True
0 c True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.