TypeError Traceback (most recent call last) Cell In[37], line 3 1 originalcount =…
- User
TypeError Traceback (most recent call last) Cell In[37], line 3 1 original_count = len(df) 2 non_zero_mask = ( ----> 3 (df['Handshake_bytes'].apply(len) > 0) & 4 (df['Client_bytes'].apply(len) > 0) & 5 (df['Server_bytes'].apply(len) > 0) 6 ) 7 filtered_df = df[non_zero_mask].copy() 9 print(f"Удалено {original_count - len(filtered_df)} строк с пустыми байтовыми строками.")
File ~/miniconda3/envs/ml/lib/python3.13/site-packages/pandas/core/series.py:4924, in Series.apply(self, func, convert_dtype, args, by_row, **kwargs) 4789 def apply( 4790 self, 4791 func: AggFuncType, (...) 4796 **kwargs, 4797 ) -> DataFrame | Series: 4798 """ 4799 Invoke function on values of Series. 4800 (...) 4915 dtype: float64 4916 """ 4917 return SeriesApply( 4918 self, 4919 func, 4920 convert_dtype=convert_dtype, 4921 by_row=by_row, 4922 args=args, 4923 kwargs=kwargs, -> 4924 ).apply()
File ~/miniconda3/envs/ml/lib/python3.13/site-packages/pandas/core/apply.py:1427, in SeriesApply.apply(self) 1424 return self.apply_compat() 1426 # self.func is Callable -> 1427 return self.apply_standard()
File ~/miniconda3/envs/ml/lib/python3.13/site-packages/pandas/core/apply.py:1507, in SeriesApply.apply_standard(self) 1501 # row-wise access 1502 # apply doesn't have a na_action keyword and for backward compat reasons 1503 # we need to give na_action="ignore" for categorical data. 1504 # TODO: remove the na_action="ignore" when that default has been changed in 1505 # Categorical (GH51645). 1506 action = "ignore" if isinstance(obj.dtype, CategoricalDtype) else None -> 1507 mapped = obj._map_values( 1508 mapper=curried, na_action=action, convert=self.convert_dtype 1509 ) 1511 if len(mapped) and isinstance(mapped[0], ABCSeries): 1512 # GH#43986 Need to do list(mapped) in order to get treated as nested 1513 # See also GH#25959 regarding EA support 1514 return obj._constructor_expanddim(list(mapped), index=obj.index)
File ~/miniconda3/envs/ml/lib/python3.13/site-packages/pandas/core/base.py:921, in IndexOpsMixin._map_values(self, mapper, na_action, convert) 918 if isinstance(arr, ExtensionArray): 919 return arr.map(mapper, na_action=na_action) --> 921 return algorithms.map_array(arr, mapper, na_action=na_action, convert=convert)
File ~/miniconda3/envs/ml/lib/python3.13/site-packages/pandas/core/algorithms.py:1743, in map_array(arr, mapper, na_action, convert) 1741 values = arr.astype(object, copy=False) 1742 if na_action is None: -> 1743 return lib.map_infer(values, mapper, convert=convert) 1744 else: 1745 return lib.map_infer_mask( 1746 values, mapper, mask=isna(values).view(np.uint8), convert=convert 1747 )
File lib.pyx:2972, in pandas._libs.lib.map_infer()
TypeError: object of type 'float' has no len()
Как найти строку с типом float, которая мешает?
- Assistant
Ошибка
TypeError: object of type 'float' has no len()возникает, потому что в столбцеdf['Handshake_bytes'](или в других столбцах, которые вы проверяете) есть значения типаfloat(например,NaN), а функцияlen()не применима к числам.Чтобы найти строки, где в этих столбцах встречаются значения не строкового типа (например,
float), можно сделать так:# Проверяем, какие строки содержат значения, для которых нельзя применить len() mask_handshake = df['Handshake_bytes'].apply(lambda x: not isinstance(x, (str, bytes))) mask_client = df['Client_bytes'].apply(lambda x: not isinstance(x, (str, bytes))) mask_server = df['Server_bytes'].apply(lambda x: not isinstance(x, (str, bytes))) # Объединяем маски, чтобы найти все проблемные строки problematic_rows = df[mask_handshake | mask_client | mask_server] print(problematic_rows)Этот код выведет все строки, где в указанных столбцах есть значения, не являющиеся строками или байтовыми строками (например,
float,NaNи т.п.).
Дополнительно: как безопасно фильтровать строки с непустыми строками
Если вы хотите отфильтровать строки, где в этих столбцах есть непустые строки, можно сделать так:
non_zero_mask = ( df['Handshake_bytes'].apply(lambda x: isinstance(x, (str, bytes)) and len(x) > 0) & df['Client_bytes'].apply(lambda x: isinstance(x, (str, bytes)) and len(x) > 0) & df['Server_bytes'].apply(lambda x: isinstance(x, (str, bytes)) and len(x) > 0) ) filtered_df = df[non_zero_mask].copy()Так вы избежите ошибки
len()на нестроковых значениях.
Если нужно, могу помочь с обработкой
NaNили приведением типов. Просто скажите!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.