pandas 我只是尝试用现有数据舍入到最接近的整数,当我尝试舍入函数时,总是返回错误

zpjtge22  于 2023-03-28  发布在  其他
关注(0)|答案(2)|浏览(144)

我正在使用Pandas对视频游戏信息进行排序。我有我需要的数据,我所需要的只是将结果四舍五入到最近的整数。

# Create a data frame with the properly queried and sorted data
semi1 = (ratingSort.sort_values(by=['numVotes', 'averageRating'], ascending=False))

# Create a data frame with only the required columns
semi2 = semi1[['primaryTitle', 'startYear', 'averageRating', 'numVotes']]

# Create a data frame with a subset of records
final = (semi2.head(10))

final

(Data正确打印在此处)
然后我试着四舍五入到最接近的整数:

['User_Count'].round(decimals=0)

这将返回和错误。我还尝试了:

final = ['User_Count'].round(decimals=0)

列标题为“User_Count”和“Name”

hlswsv35

hlswsv351#

此错误是由以下行引起的:
['User_Count'].round(decimals=0)
当你在'User_Count'周围使用sqaure括号时,python正在创建一个以'User_Count'元素为字符串的列表,并试图使用它调用round。由于列表没有一个名为round的方法,因此会引发此错误。

8yparm6h

8yparm6h2#

发生此错误的原因是您在仅包含单词'User_Count'的列表上调用round。当您编写['User_Count ']时,python将创建一个包含一个元素的列表,该元素将是字符串'User_Count '。您需要做的是在pandas dataframe上调用round函数。
首先,将“User_Count”列添加到最终的 Dataframe 中:

semi2 = semi1[['primaryTitle', 'startYear', 'averageRating', 'numVotes', 'User_Count']]
final = semi2.head(10)

接下来,在结果 Dataframe 中的“User_Count”列上调用round函数

final['User_Count'].round(decimals=0)

有关更多信息,请参阅panda.DataFrame.round函数的文档:link

相关问题