在Python中很难将5星等级转换为“正”和“负”等级

2024-04-26 13:58:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv,它包含1-5的整数。我正在尝试编写一个新的csv,它接受原始csv中的任何1和2,并返回“负”,然后所有3、4和5都返回为“正”。以下是我到目前为止的资料(我正在使用Pandas&TextBlob供参考):

ratings = pd.read_csv(r'/Users/jackcarlson/Downloads/amazon-cell-phones-reviews/only_rating.csv')

sentimentals = []
sentlist = [1,2]

for i in ratings.itertuples():
    if i in sentlist:
            neg = True
    if neg:
        sentimentals.append("negative")
    else:
        sentimentals.append("positive")
print(sentimentals)

with open('/Users/jackcarlson/Downloads/starreview.txt', 'w') as filehandle:
    for listitem in sentimentals:
        filehandle.write('%s\n' % listitem)

以下是我的csv的外观:

enter image description here

我的for循环每行只返回“负”。我确信这是一个简单的错误(我对Python非常陌生),任何帮助都是惊人的。谢谢您!你知道吗


Tags: csvinforifdownloads整数usersratings
3条回答

如果只有一列,则不需要将行作为元组循环。相反,只循环该列:

for i in ratings['rating']:
    if i in sentlist:
        sentimentals.append("negative")
    else:
        sentimentals.append("positive")

下面是使用^{}^{}方法处理pandas的方法:

d = {1: 'negative',
     2: 'negative',
     3: 'positive',
     4: 'positive',
     5: 'postive'}

ratings = pd.read_csv(r'/Users/jackcarlson/Downloads/amazon-cell-phones-reviews/only_rating.csv')

(ratings['rating'].map(d)
 .to_csv('/Users/jackcarlson/Downloads/starreview.txt',
         index=False, header=False))

另一种方法是使用^{}而不是循环来创建"sentimentals"

sentimentals = ['negative' if x <= 2 else 'positive' for x in ratings['rating']]

这应该管用。你知道吗

for i in ratings.itertuples():
    if i in sentlist:
        sentimentals.append("negative")
    else:
        sentimentals.append("positive")

相关问题 更多 >