简体   繁体   中英

ValueError: Unknown format code 'f' for object of type 'str' - why do I get this the second time but not the first time?

Below is my code. I'm trying to print both the Top 250 lines and the Bottom 250 lines, and strategized to make a copy of my main dataframe, re-sort, and then format the percentages into a string format with a "%" sign. Unfortunately I'm getting a ValueError: Unknown format code 'f' for object of type 'str' on the line with upreportdataframe, but not with downreportdataframe. Why would this be?

Does this have something to do with how the dataframe is copied?

upreportdataframe.sort(['dailypctchange'], ascending = False, inplace=True)
downreportdataframe = upreportdataframe
downreportdataframe.is_copy = False
downreportdataframe.sort(['dailypctchange'], ascending = True, inplace = True)
downreportdataframe['dailypctchange'] = pd.Series(
    ["{0:.2f}%".format(val * 100)
     for val in downreportdataframe['dailypctchange']],
    downreportdataframe.index)

upreportdataframe['dailypctchange'] = pd.Series(
    ["{0:.2f}%".format(val * 100)
     for val in upreportdataframe['dailypctchange']],
    upreportdataframe.index)

downreportdataframe is not a copy of upreportdataframe ; it is instead just another reference to the same object .

If you wanted a copy, use the dataframe.copy() method :

downreportdataframe = upreportdataframe.copy()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM