Python 尝试使用dataframe字典
我在执行此代码时遇到问题:Python 尝试使用dataframe字典,python,pandas,dataframe,Python,Pandas,Dataframe,我在执行此代码时遇到问题: def create_binary_nw(row): if row['Net_withdrawal'] <=0: return 0 else: return 1 # a class class create_storages: def __init__(self,file1,file2): self.file1 = file1 self.file2 = file2
def create_binary_nw(row):
if row['Net_withdrawal'] <=0:
return 0
else:
return 1
# a class
class create_storages:
def __init__(self,file1,file2):
self.file1 = file1
self.file2 = file2
def open_storages(self):
wb = load_workbook(self.file1)#load the file to a workbook
ws = wb.sheetnames # get all the names of Excel sheets in order to construct a dictionary
storages = {}# a dictionary
storages = pd.read_excel(self.file1, sheet_name = None)# adding the dictionary element
return [storages, ws]
def complete_storages(self):
[storages,ws] = self.open_storages()
for i in range(len(ws)):
NW = storages[ws[i]]['withdrawal']-storages[ws[i]]['injection']
storages[ws[i]].insert(7, "Net_withdrawal",NW, True)#adding the column NW NO PROBLEM
storages[ws[i]]['Net_withdrawal_binary']= storages[ws[i]].apply(create_binary_nw(storages[ws[i]]),axis=1)#THE PROBLEM IS HERE!!!
enter code here
# execution
class_storage = create_storages('storage_data.xlsx','price_data.csv')
#[storage1,ws1] = class_storage.open_storages()
class_storage.complete_storages()
我认为错误来自我的函数create_binary,当我将它应用于storages[ws[I]]时,它是一个数据帧字典(storages是一个字典,storages[ws[I]]是一个数据帧,它有一个名为“Net_retrach”的列,这是一列浮点数)
谢谢你的回答。错误消息告诉你的是,如果你想比较一组值是否小于0(
错误消息告诉你的是,如果你想比较一组值是否小于0(好,谢谢你的回答。的确,存储[ws[i]]['Net_Retraction]是数据帧的一个列,而不是数字。感谢您的回答。实际上,storages[ws[i]['Net_Retraction]是数据帧的一个列,而不是数字
> ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().
import numpy as np
a = np.array([1,1,0])
if a > 0: # fails here, array can't be compared with a single value
print("yay")
storages[ws[i]]['Net_withdrawal_binary']= storages[ws[i]].apply(create_binary_nw(storages[ws[i]]),axis=1)#THE PROBLEM IS HERE!!!
storages[ws[i]]['Net_withdrawal_binary']= storages[ws[i]].apply(lambda a: create_binary_nw(a),axis=1)