パンダread_csv混合タイプの質問



Pandas Read_csv Mixed Types Question



まず、問題の原因

私はカンダスを使用してcsvを読み取り、いくつかの条件でデータをクリーンアップしました。クリーンアップしたデータが間違っていると感じました。 Python独自のcsvモジュールを使用してクリーンアップしました。 2つの方法のデータに一貫性がないことがわかったので、調べることにしました。

第二に、最初にパンダの警告に注意してください

DtypeWarning: Columns (1,5,7,16,......) have mixed types. Specify dtype option on import or set low_memory=False. The meaning is: the data types of columns 1,5,7,16.... are different. Debugging went in and saw that pandas did the same data in the same column when reading. The values ​​are identified as different types. For example, the data with the value of 0 in column 3 of 2000 rows is identified as Int type. Data with a value of 0 in the third column of 4000 rows is identified as a str type.

この問題を解決するには、次の2つのオプションがあります。



# 1. Set the dtype parameter of read_csv, specify the data type of the field. pd.read_csv(sio, dtype={'user_id': int, 'username': object}) # 2. Set the low_memory parameter of read_csv to False pd.read_csv(sio, low_memory=False})

私が遭遇し始めたパンダとcsvモジュールでデータをクリーニングした結果の不一致は、特定のフィールドのデータ型を推測するときのパンダの推測結果の一貫性がないためです。

第三に、low_memoryはどのように問題を解決しますか?

pandas read csvファイルは、デフォルトでブロックごとに読み取られます。つまり、一度にすべて読み取られるわけではありません。
さらに、パンダはデータのタイプを完全に推測しているため、パンダはデータを読み取るたびにcsvフィールドのデータ型を推測します。したがって、パンダは異なるブロックを読み取っている可能性があります。同じフィールドのデータ型の推測結果に一貫性がありません。
low_memory = Falseパラメータが設定された後、パンダはcsv内のすべてのデータを一度に読み取り、フィールドのデータ型を一意に推測します。これにより、同じフィールドで混合タイプの問題が発生することはありません。
しかし、この方法は本当に悪いです。 csvファイルが大きすぎると、オーバーフローします。したがって、最初のソリューションを使用することをお勧めします。



The official pandas documentation explains low_memory: low_memory : boolean, default True Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set False, or specify the type with the dtype parameter. Note that the entire file is read into a single DataFrame regardless, use the chunksize or iterator parameter to return the data in chunks. (Only valid with C parser)