Home > Net >  Changing variable type - Pandas
Changing variable type - Pandas

Time:02-04

In writing to a file, my method checks whether or not a DataFrame exists. This is done by passing a DataFrame into my method or a value of -1 which signifies a dataframe does not exist in this calling. However, in the times it does exist I am subjected to the following error:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Below is my method:

def writeToFile(valueToWrite, columnCount, dataFrame): 
    """Method allows for writing specifics to file based on column count variable
    """
    fileWriter = open(outputFile, "w") #Open file for writing data too

    if dataFrame != -1:
        for x in range(len(dataFrame.columns)): #Write column headers to file
            fileWriter.write(str(dataFrame.columns[x]) '\t')

    if columnCount == 0:
        fileWriter.write('\n' str(valueToWrite))
    elif columnCount > 0:
        fileWriter.write(', ' str(valueToWrite))

How would I enable writeToFile to check whether a dataframe is passed or not?

CodePudding user response:

If dataframe is not -1 but instead a real dataframe, pandas will attempt to map val != -1 to each of its values and return a new dataframe. The newly created dataframe is then evaluated to a boolean. That leads to your error. I suggest you use None instead of -1 as a default failure value.

def writeToFile(valueToWrite, columnCount, dataFrame=None): 
    """Method allows for writing specifics to file based on column count variable
    """
    fileWriter = open(outputFile, "w") #Open file for writing data too

    if dataFrame is not None:
        for x in range(len(dataFrame.columns)): #Write column headers to file
            fileWriter.write(str(dataFrame.columns[x]) '\t')

    if columnCount == 0:
        fileWriter.write('\n' str(valueToWrite))
    elif columnCount > 0:
        fileWriter.write(', ' str(valueToWrite))

If you need to keep the -1 failure value, do an instance check:

def writeToFile(valueToWrite, columnCount, dataFrame): 
    """Method allows for writing specifics to file based on column count variable
    """
    fileWriter = open(outputFile, "w") #Open file for writing data too

    if not isinstance(dataFrame, int) or dataFrame != -1:
        for x in range(len(dataFrame.columns)): #Write column headers to file
            fileWriter.write(str(dataFrame.columns[x]) '\t')

    if columnCount == 0:
        fileWriter.write('\n' str(valueToWrite))
    elif columnCount > 0:
        fileWriter.write(', ' str(valueToWrite))

The part after or is only evaluated if the part before or is False, meaning the second part is only evaluated if dataFrame is an integer.

  •  Tags:  
  • Related