根据多个列条件筛选行时出错,“ValueError:invalid literal for int()with base 10:”

2024-09-30 22:16:35 发布

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

当我尝试使用多个列条件筛选数据帧时,得到一个'ValueError:invalid literal for int(),以10为基数:'

下面是设置熊猫数据帧的代码。警告:它将下载6 mb的数据。如果太担心的话,可以在googlecolab中运行。你知道吗

导入数据和下载数据的代码

#Import stuff
import re
import os
import zipfile
from urllib.request import urlretrieve
from os.path import isfile, isdir
import requests
#Define Download Function
def download_file_from_google_drive(id, destination):
    URL = "https://docs.google.com/uc?export=download"

    session = requests.Session()

    response = session.get(URL, params = { 'id' : id }, stream = True)
    token = get_confirm_token(response)

    if token:
        params = { 'id' : id, 'confirm' : token }
        response = session.get(URL, params = params, stream = True)

    save_response_content(response, destination)    

def get_confirm_token(response):
    for key, value in response.cookies.items():
        if key.startswith('download_warning'):
            return value

    return None

def save_response_content(response, destination):
    CHUNK_SIZE = 32768

    with open(destination, "wb") as f:
        for chunk in response.iter_content(CHUNK_SIZE):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)

#Download data
download_file_from_google_drive('1sZk3WWgdyHLru7q1KSWQwCT4nwwzHlpY', 'TheAnimeList.csv')

设置数据帧的代码

download_file_from_google_drive('1sZk3WWgdyHLru7q1KSWQwCT4nwwzHlpY', 'TheAnimeList.csv')

animeuser = pd.read_csv('TheAnimeList.csv' )
animeuser = animeuser[['anime_id','title_english', 'popularity', 'rank']]
animeuser.head()


anime_id    title_english   popularity  rank
0   11013   Inu X Boku Secret Service   231 1274.0
1   2104    My Bride is a Mermaid   366 727.0
2   5262    Shugo Chara!! Doki  1173    1508.0
3   721 Princess Tutu   916 307.0
4   12365   Bakuman.    426 50.0

我正在尝试根据列条件筛选行。首先我试过了

animeuser = animeuser[  (animeuser.popularity >= 3000) | (animeuser.rank >= 3000)  ]

但这给了我这个错误

TypeError                                 Traceback (most recent call last)
<ipython-input-39-8fb6d8508f25> in <module>()
----> 1 animeuser = animeuser[  (animeuser.popularity >= 3000) | (animeuser.rank >= 3000)  ]

TypeError: '>=' not supported between instances of 'method' and 'int'

然后我试着

animeuser =  animeuser[ ( animeuser.astype(int)['popularity'] >= 3000 ) | ( animeuser.astype(int)['rank'] >= 3000 ) ] 

但这给了我这个错误

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-40-a2ea65786b2a> in <module>()
----> 1 animeuser =  animeuser[ ( animeuser.astype(int)['popularity'] >= 3000 ) | ( animeuser.astype(int)['rank'] >= 3000 ) ]

/usr/local/lib/python3.6/dist-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs)
    116                 else:
    117                     kwargs[new_arg_name] = new_arg_value
--> 118             return func(*args, **kwargs)
    119         return wrapper
    120     return _deprecate_kwarg

/usr/local/lib/python3.6/dist-packages/pandas/core/generic.py in astype(self, dtype, copy, errors, **kwargs)
   4002         # else, only a single dtype is given
   4003         new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors,
-> 4004                                      **kwargs)
   4005         return self._constructor(new_data).__finalize__(self)
   4006 

/usr/local/lib/python3.6/dist-packages/pandas/core/internals.py in astype(self, dtype, **kwargs)
   3460 
   3461     def astype(self, dtype, **kwargs):
-> 3462         return self.apply('astype', dtype=dtype, **kwargs)
   3463 
   3464     def convert(self, **kwargs):

/usr/local/lib/python3.6/dist-packages/pandas/core/internals.py in apply(self, f, axes, filter, do_integrity_check, consolidate, **kwargs)
   3327 
   3328             kwargs['mgr'] = self
-> 3329             applied = getattr(b, f)(**kwargs)
   3330             result_blocks = _extend_blocks(applied, result_blocks)
   3331 

/usr/local/lib/python3.6/dist-packages/pandas/core/internals.py in astype(self, dtype, copy, errors, values, **kwargs)
    542     def astype(self, dtype, copy=False, errors='raise', values=None, **kwargs):
    543         return self._astype(dtype, copy=copy, errors=errors, values=values,
--> 544                             **kwargs)
    545 
    546     def _astype(self, dtype, copy=False, errors='raise', values=None,

/usr/local/lib/python3.6/dist-packages/pandas/core/internals.py in _astype(self, dtype, copy, errors, values, klass, mgr, **kwargs)
    623 
    624                 # _astype_nansafe works fine with 1-d only
--> 625                 values = astype_nansafe(values.ravel(), dtype, copy=True)
    626                 values = values.reshape(self.shape)
    627 

/usr/local/lib/python3.6/dist-packages/pandas/core/dtypes/cast.py in astype_nansafe(arr, dtype, copy)
    690     elif arr.dtype == np.object_ and np.issubdtype(dtype.type, np.integer):
    691         # work around NumPy brokenness, #1987
--> 692         return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape)
    693 
    694     if dtype.name in ("datetime64", "timedelta64"):

pandas/_libs/lib.pyx in pandas._libs.lib.astype_intsafe()

pandas/_libs/src/util.pxd in util.set_value_at_unsafe()

ValueError: invalid literal for int() with base 10: 'Inu X Boku Secret Service'

字符串'Inu X Boku Secret Service'属于数据帧第一行的'title\u english'列。但“rank”和“popularity”列显示为float和int。你知道吗

我甚至试过查看数据类型

animeuser.dtypes

anime_id           int64
title_english     object
popularity         int64
rank             float64
dtype: object

一切都井然有序。你知道吗


Tags: inselfidpandasreturnresponselibkwargs
2条回答

带声明

animeuser.astype(int)['popularity']

您正在尝试转换为int所有animeuser列。字符串列出错。试试看

animeuser['popularity']

您面临的第一个错误是因为^{}pandas.DataFrame的方法。方法通过属性表示法优先于列访问。因此,为了访问数据,需要使用括号表示法:animeuser['rank']。你知道吗

出现第二个错误是因为您试图将整个数据帧表示为int,这对于不同的列是不可能的。这只能用于'rank''popularity'列。你知道吗

相关问题 更多 >