import pandas as pd
data = {'kol_click':[1, 8, 4, 2, 1, '', 18, '', 3, 10]}
df1 = pd.DataFrame(data)
df1['kol_click_1'] = df1['kol_click'].str.replace('', '0')
print(df1.head(10))
kol_click kol_click_1
0 1 NaN
1 8 NaN
2 4 NaN
3 2 NaN
4 1 NaN
5 0
6 18 NaN
7 0
8 3 NaN
9 10 NaN
Почему числа поменялись на NaN ? Как заменить пустые строки на нулевые значения?
![]()
задан 3 мар 2020 в 13:23
1
Проблема вызвана смешением целых чисел и строк в одном столбце. Pandas воспринимает тип такого столбеца как object:
In [17]: df1.dtypes
Out[17]:
kol_click object
dtype: object
Но комфортно работать c таким столбцом как с обычным строковым столбцом не получится:
In [25]: df1['kol_click'].str[:10]
Out[25]:
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5
6 NaN
7
8 NaN
9 NaN
Name: kol_click, dtype: object
In [26]: df1['kol_click'].astype(str).str[:10]
Out[26]:
0 1
1 8
2 4
3 2
4 1
5
6 18
7
8 3
9 10
Name: kol_click, dtype: object
Решение — попробуйте так:
In [22]: df1['kol_click_1'] = pd.to_numeric(df1['kol_click'], errors='coerce').fillna(0)
In [23]: df1
Out[23]:
kol_click kol_click_1
0 1 1.0
1 8 8.0
2 4 4.0
3 2 2.0
4 1 1.0
5 0.0
6 18 18.0
7 0.0
8 3 3.0
9 10 10.0
In [24]: df1.dtypes
Out[24]:
kol_click object
kol_click_1 float64
dtype: object
![]()
0xdb
51.2k194 золотых знака56 серебряных знаков227 бронзовых знаков
ответ дан 3 мар 2020 в 13:36
![]()
1
I am using pandas to open a text document as follows.
input_data = pd.read_csv('input.tsv', header=0, delimiter="t", quoting=3 )
L= input_data["title"] + '. ' + input_data["description"]
I found that some of my text equals to nan. Therefore, I tried the following approach.
import math
for text in L:
if not math.isnan(text):
print(text)
However, this returned me the following error TypeError: must be real number, not str
Is there a way to identify string nan values in python?
My tsvlooks as follows
id title description major minor
27743058 Partial or total open meniscectomy? : A prospective, randomized study. In order to compare partial with total meniscectomy a prospective clinical study of 200 patients was carried out. At arthrotomy 100 patients were allocated to each type of operation. The two groups did not differ in duration of symptoms, age distribution, or sex ratio. The operations were performed as conventional arthrotomies. One hundred and ninety two of the patients were seen at follow up 2 and 12 months after operation. There was no difference in the period off work between the two groups. One year after operation, 6 of the 98 patients treated with partial meniscectomy had undergone further operation. In all posterior tears were found at both procedures. Among the 94 patients undergoing total meniscectomy, 4 required further operation. In each, part of the posterior horn had been left at the primary procedure. One year after operation significantly more patients who had undergone partial meniscectomy had been relieved of symptoms. However, the two groups did not show any difference in the degree of radiological changes present. ### ###
27743057 Synovial oedema is a frequent complication in arthroscopic procedures performed with normal saline as the irrigating fluid. The authors have studied the effect of saline solution, Ringer lactate, 5% Dextran and 10% Dextran in normal saline on 12 specimens of human synovial membrane. They found that 10% Dextran in normal saline decreases the water content of the synovium without causing damage, and recommend this solution for procedures lasting longer than 30 minutes. ### ###
I am using pandas to open a text document as follows.
input_data = pd.read_csv('input.tsv', header=0, delimiter="t", quoting=3 )
L= input_data["title"] + '. ' + input_data["description"]
I found that some of my text equals to nan. Therefore, I tried the following approach.
import math
for text in L:
if not math.isnan(text):
print(text)
However, this returned me the following error TypeError: must be real number, not str
Is there a way to identify string nan values in python?
My tsvlooks as follows
id title description major minor
27743058 Partial or total open meniscectomy? : A prospective, randomized study. In order to compare partial with total meniscectomy a prospective clinical study of 200 patients was carried out. At arthrotomy 100 patients were allocated to each type of operation. The two groups did not differ in duration of symptoms, age distribution, or sex ratio. The operations were performed as conventional arthrotomies. One hundred and ninety two of the patients were seen at follow up 2 and 12 months after operation. There was no difference in the period off work between the two groups. One year after operation, 6 of the 98 patients treated with partial meniscectomy had undergone further operation. In all posterior tears were found at both procedures. Among the 94 patients undergoing total meniscectomy, 4 required further operation. In each, part of the posterior horn had been left at the primary procedure. One year after operation significantly more patients who had undergone partial meniscectomy had been relieved of symptoms. However, the two groups did not show any difference in the degree of radiological changes present. ### ###
27743057 Synovial oedema is a frequent complication in arthroscopic procedures performed with normal saline as the irrigating fluid. The authors have studied the effect of saline solution, Ringer lactate, 5% Dextran and 10% Dextran in normal saline on 12 specimens of human synovial membrane. They found that 10% Dextran in normal saline decreases the water content of the synovium without causing damage, and recommend this solution for procedures lasting longer than 30 minutes. ### ###
В предыдущих разделах вы видели, как легко могут образовываться недостающие данные. В структурах они определяются как значения NaN (Not a Value). Такой тип довольно распространен в анализе данных.
Но pandas спроектирован так, чтобы лучше с ними работать. Дальше вы узнаете, как взаимодействовать с NaN, чтобы избегать возможных проблем. Например, в библиотеке pandas вычисление описательной статистики неявно исключает все значения NaN.
Если нужно специально присвоить значение NaN элементу структуры данных, для этого используется np.NaN (или np.nan) из библиотеки NumPy.
>>> ser = pd.Series([0,1,2,np.NaN,9],
... index=['red','blue','yellow','white','green'])
>>> ser
red 0.0
blue 1.0
yellow 2.0
white NaN
green 9.0
dtype: float64
>>> ser['white'] = None
>>> ser
red 0.0
blue 1.0
yellow 2.0
white NaN
green 9.0
dtype: float64
Фильтрование значений NaN
Есть несколько способов, как можно избавиться от значений NaN во время анализа данных. Это можно делать вручную, удаляя каждый элемент, но такая операция сложная и опасная, к тому же не гарантирует, что вы действительно избавились от всех таких значений. Здесь на помощь приходит функция dropna().
>>> ser.dropna()
red 0.0
blue 1.0
yellow 2.0
green 9.0
dtype: float64
Функцию фильтрации можно выполнить и прямо с помощью notnull() при выборе элементов.
>>> ser[ser.notnull()]
red 0.0
blue 1.0
yellow 2.0
green 9.0
dtype: float64
В случае с Dataframe это чуть сложнее. Если использовать функцию pandas dropna() на таком типе объекта, который содержит всего одно значение NaN в колонке или строке, то оно будет удалено.
>>> frame3 = pd.DataFrame([[6,np.nan,6],[np.nan,np.nan,np.nan],[2,np.nan,5]],
... index = ['blue','green','red'],
... columns = ['ball','mug','pen'])
>>> frame3
| ball | mug | pen | |
|---|---|---|---|
| blue | 6.0 | NaN | 6.0 |
| green | NaN | NaN | NaN |
| red | 2.0 | NaN | 5.0 |
>>> frame3.dropna()
Empty DataFrame
Columns: [ball, mug, pen]
Index: []
Таким образом чтобы избежать удаления целых строк или колонок нужно использовать параметр how, присвоив ему значение all. Это сообщит функции, чтобы она удаляла только строки или колонки, где все элементы равны NaN.
>>> frame3.dropna(how='all')
| ball | mug | pen | |
|---|---|---|---|
| blue | 6.0 | NaN | 6.0 |
| red | 2.0 | NaN | 5.0 |
Заполнение NaN
Вместо того чтобы отфильтровывать значения NaN в структурах данных, рискуя удалить вместе с ними важные элементы, можно заменять их на другие числа. Для этих целей подойдет fillna(). Она принимает один аргумент — значение, которым нужно заменить NaN.
>>> frame3.fillna(0)
| ball | mug | pen | |
|---|---|---|---|
| blue | 6.0 | 0.0 | 6.0 |
| green | 0.0 | 0.0 | 0.0 |
| red | 2.0 | 0.0 | 5.0 |
Или же NaN можно заменить на разные значения в зависимости от колонки, указывая их и соответствующие значения.
>>> frame3.fillna({'ball':1,'mug':0,'pen':99})
| ball | mug | pen | |
|---|---|---|---|
| blue | 6.0 | 0.0 | 6.0 |
| green | 1.0 | 0.0 | 99.0 |
| red | 2.0 | 0.0 | 5.0 |
Обучение с трудоустройством
17 авг. 2022 г.
читать 2 мин
Одна ошибка, с которой вы можете столкнуться при использовании pandas:
ValueError : cannot convert float NaN to integer
Эта ошибка возникает, когда вы пытаетесь преобразовать столбец в кадре данных pandas из числа с плавающей запятой в целое число, но столбец содержит значения NaN.
В следующем примере показано, как исправить эту ошибку на практике.
Как воспроизвести ошибку
Предположим, мы создаем следующие Pandas DataFrame:
import pandas as pd
import numpy as np
#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
'assists': [5, 7, 7, 9, 12, 9, 9, 4],
'rebounds': [11, np.nan , 10, 6, 5, np.nan , 9, 12]})
#view DataFrame
df
points assists rebounds
0 25 5 11
1 12 7 NaN
2 15 7 10
3 14 9 6
4 19 12 5
5 23 9 NaN
6 25 9 9
7 29 4 12
В настоящее время столбец «отскоки» имеет тип данных «плавающий».
#print data type of 'rebounds' column
df['rebounds']. dtype
dtype('float64')
Предположим, мы пытаемся преобразовать столбец «отскоки» из числа с плавающей запятой в целое число:
#attempt to convert 'rebounds' column from float to integer
df['rebounds'] = df['rebounds'].astype (int)
ValueError : cannot convert float NaN to integer
Мы получаем ValueError , потому что значения NaN в столбце «отскоков» не могут быть преобразованы в целые значения.
Как исправить ошибку
Способ исправить эту ошибку состоит в том, чтобы иметь дело со значениями NaN, прежде чем пытаться преобразовать столбец из числа с плавающей запятой в целое число.
Мы можем использовать следующий код, чтобы сначала определить строки, содержащие значения NaN:
#print rows in DataFrame that contain NaN in 'rebounds' column
print(df[df['rebounds']. isnull ()])
points assists rebounds
1 12 7 NaN
5 23 9 NaN
Затем мы можем либо удалить строки со значениями NaN, либо заменить значения NaN каким-либо другим значением перед преобразованием столбца из числа с плавающей запятой в целое число:
Метод 1: удаление строк со значениями NaN
#drop all rows with NaN values
df = df.dropna ()
#convert 'rebounds' column from float to integer
df['rebounds'] = df['rebounds'].astype (int)
#view updated DataFrame
df
points assists rebounds
0 25 5 11
2 15 7 10
3 14 9 6
4 19 12 5
6 25 9 9
7 29 4 12
#view class of 'rebounds' column
df['rebounds']. dtype
dtype('int64')
Способ 2: заменить значения NaN
#replace all NaN values with zeros
df['rebounds'] = df['rebounds']. fillna ( 0 )
#convert 'rebounds' column from float to integer
df['rebounds'] = df['rebounds'].astype (int)
#view updated DataFrame
df
points assists rebounds
0 25 5 11
1 12 7 0
2 15 7 10
3 14 9 6
4 19 12 5
5 23 9 0
6 25 9 9
7 29 4 12
#view class of 'rebounds' column
df['rebounds']. dtype
dtype('int64')
Обратите внимание, что оба метода позволяют избежать ошибки ValueError и успешно преобразовать столбец с плавающей запятой в столбец с целым числом.
Дополнительные ресурсы
В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:
Как исправить: столбцы перекрываются, но суффикс не указан
Как исправить: объект «numpy.ndarray» не имеет атрибута «добавлять»
Как исправить: при использовании всех скалярных значений необходимо передать индекс
