IT story

Pandas 또는 Numpy Nan을 None으로 대체하여 MysqlDB와 함께 사용

hot-time 2020. 8. 31. 08:24
반응형

Pandas 또는 Numpy Nan을 None으로 대체하여 MysqlDB와 함께 사용


MysqlDB를 사용하여 mysql 데이터베이스에 Pandas 데이터 프레임 (또는 numpy 배열을 사용할 수 있음)을 쓰려고합니다. MysqlDB는 'nan'을 이해하지 못하는 것 같고 내 데이터베이스는 nan이 필드 목록에 없다는 오류를 표시합니다. 'nan'을 NoneType으로 변환하는 방법을 찾아야합니다.

어떤 아이디어?


@bogatron이 맞습니다.를 사용할 수 있습니다 where. pandas에서 기본적으로이 작업을 수행 할 수 있다는 점은 주목할 가치가 있습니다.

df1 = df.where((pd.notnull(df)), None)

참고 :이의 DTYPE 변경 모든 열 을을 object.

예:

In [1]: df = pd.DataFrame([1, np.nan])

In [2]: df
Out[2]: 
    0
0   1
1 NaN

In [3]: df1 = df.where((pd.notnull(df)), None)

In [4]: df1
Out[4]: 
      0
0     1
1  None

참고 : dtype모든 데이터 유형 유형을 허용하도록 DataFrames 다시 캐스팅 할 수없는 작업은 astype다음과 같습니다 fillna.

df1 = df.astype(object).replace(np.nan, 'None')

불행히도 이것도를 사용하지도이 (종료 된) 문제replaceNone볼 수 없습니다 .


제쳐두고, 대부분의 사용 사례에서 NaN을 None으로 바꿀 필요가 없다는 점에 주목할 가치가 있습니다 .pandas에서 NaN과 None 의 차이점 에 대한이 질문을 참조하십시오 .

그러나이 특정 경우에는 (적어도이 답변 당시) 그렇게 보입니다.


df = df.replace({pd.np.nan: None})

크레딧은 Github 문제 에서이 사람에게갑니다 .


당신은 대체 할 수 nan와 함께 None당신의 NumPy와 배열 :

>>> x = np.array([1, np.nan, 3])
>>> y = np.where(np.isnan(x), None, x)
>>> print y
[1.0 None 3.0]
>>> print type(y[1])
<type 'NoneType'>

뒤틀린 후 이것은 나를 위해 일했습니다.

df = df.astype(object).where(pd.notnull(df),None)

꽤 오래되었지만 나는 똑같은 문제를 우연히 발견했습니다. 다음을 시도하십시오.

df['col_replaced'] = df['col_with_npnans'].apply(lambda x: None if np.isnan(x) else x)

@Andy Hayden의 답변에 추가하면 다음과 같습니다.

Since DataFrame.mask is the opposite twin of DataFrame.where, they have the exactly same signature but with opposite meaning:

  • DataFrame.where is useful for Replacing values where the condition is False.
  • DataFrame.mask is used for Replacing values where the condition is True.

So in this question, using df.mask(df.isna(), other=None, inplace=True) might be more intuitive.

참고URL : https://stackoverflow.com/questions/14162723/replacing-pandas-or-numpy-nan-with-a-none-to-use-with-mysqldb

반응형