CSVからインポートされたデータを操作しています。パンダは一部の列を浮動小数点に変更したため、これらの列の数値は浮動小数点として表示されます。ただし、整数として、またはコンマなしで表示する必要があります。それらを整数に変換する方法、またはコンマを表示しない方法はありますか?
df = df.astype(int)
                CSVからインポートされたデータを操作しています。パンダは一部の列を浮動小数点に変更したため、これらの列の数値は浮動小数点として表示されます。ただし、整数として、またはコンマなしで表示する必要があります。それらを整数に変換する方法、またはコンマを表示しない方法はありますか?
df = df.astype(int)
                回答:
float出力を変更するには、次のようにします。
df= pd.DataFrame(range(5), columns=['a'])
df.a = df.a.astype(float)
df
Out[33]:
          a
0 0.0000000
1 1.0000000
2 2.0000000
3 3.0000000
4 4.0000000
pd.options.display.float_format = '{:,.0f}'.format
df
Out[35]:
   a
0  0
1  1
2  2
3  3
4  4df.a = df.a.astype(float)ますか?これはコピーを作成しますか(copyパラメーターのastype()使用方法がわからない)?とにかくタイプを「インプレース」に更新しますか?
                    DF.({'200': {'#': 354, '%': 0.9971830985915493},  '302': {'#': 1, '%': 0.0028169014084507044}})  、#がfloatに変換され、列ではなく行であることに注意してください。それぞれがSeries単一のユニフォームタイプしか格納できないので?
                    dtypeですか?もしそうなら、dtypeそれらをdtype object混合できるようにそれらの列を作成する必要があります。そうでない場合は、浮動小数点を使用して比較を行うときに使用することをお勧めしますnp.isclose
                    pandas.DataFrame.astype(<type>)関数を使用して、列のdtypeを操作します。
>>> df = pd.DataFrame(np.random.rand(3,4), columns=list("ABCD"))
>>> df
          A         B         C         D
0  0.542447  0.949988  0.669239  0.879887
1  0.068542  0.757775  0.891903  0.384542
2  0.021274  0.587504  0.180426  0.574300
>>> df[list("ABCD")] = df[list("ABCD")].astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0編集:
欠損値を処理するには:
>>> df
          A         B     C         D
0  0.475103  0.355453  0.66  0.869336
1  0.260395  0.200287   NaN  0.617024
2  0.517692  0.735613  0.18  0.657106
>>> df[list("ABCD")] = df[list("ABCD")].fillna(0.0).astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0次のデータフレームを検討します。
>>> df = pd.DataFrame(10*np.random.rand(3, 4), columns=list("ABCD"))
>>> print(df)
...           A         B         C         D
... 0  8.362940  0.354027  1.916283  6.226750
... 1  1.988232  9.003545  9.277504  8.522808
... 2  1.141432  4.935593  2.700118  7.739108列名のリストを使用して、複数の列のタイプを次のように変更しますapplymap()。
>>> cols = ['A', 'B']
>>> df[cols] = df[cols].applymap(np.int64)
>>> print(df)
...    A  B         C         D
... 0  8  0  1.916283  6.226750
... 1  1  9  9.277504  8.522808
... 2  1  4  2.700118  7.739108または、次の単一列の場合apply():
>>> df['C'] = df['C'].apply(np.int64)
>>> print(df)
...    A  B  C         D
... 0  8  0  1  6.226750
... 1  1  9  9  8.522808
... 2  1  4  2  7.739108ValueError: ('cannot convert float NaN to integer', u'occurred at index <column_name>')
                    df['C'] = df['C'].dropna().apply(np.int64)
                    これは、pandas.DataFrameNaN値を持つ可能性がある場合も考慮して、floatからintegerにさらに多くの列を変換する場合の迅速な解決策です。
cols = ['col_1', 'col_2', 'col_3', 'col_4']
for col in cols:
   df[col] = df[col].apply(lambda x: int(x) if x == x else "")else x)and else None)で試しましたが、結果はまだ浮動小数点数なので、を使用しましたelse ""。
""すべての値に適用されますcol
                    @Ryan Gで言及したpandas.DataFrame.astype(<type>)メソッドの使用法を拡張すると、errors=ignore引数を使用して、エラーを生成しない列のみを変換できます。これにより、特に構文が簡略化されます。明らかに、エラーを無視するときは注意が必要ですが、このタスクには非常に便利です。
>>> df = pd.DataFrame(np.random.rand(3, 4), columns=list('ABCD'))
>>> df *= 10
>>> print(df)
...           A       B       C       D
... 0   2.16861 8.34139 1.83434 6.91706
... 1   5.85938 9.71712 5.53371 4.26542
... 2   0.50112 4.06725 1.99795 4.75698
>>> df['E'] = list('XYZ')
>>> df.astype(int, errors='ignore')
>>> print(df)
...     A   B   C   D   E
... 0   2   8   1   6   X
... 1   5   9   5   4   Y
... 2   0   4   1   4   Zpandas.DataFrame.astype docs から:
エラー:{'raise'、 'ignore'}、デフォルトは 'raise'
提供されたdtypeの無効なデータに対する例外の発生を制御します。
- raise:例外を発生させる
- ignore:例外を抑制します。エラー時に元のオブジェクトを返す
バージョン0.20.0の新機能。
>>> import pandas as pd
>>> right = pd.DataFrame({'C': [1.002, 2.003], 'D': [1.009, 4.55], 'key': ['K0', 'K1']})
>>> print(right)
           C      D key
    0  1.002  1.009  K0
    1  2.003  4.550  K1
>>> right['C'] = right.C.astype(int)
>>> print(right)
       C      D key
    0  1  1.009  K0
    1  2  4.550  K1>>> df = pd.DataFrame(np.random.rand(5, 4) * 10, columns=list('PQRS'))
>>> print(df)
...     P           Q           R           S
... 0   4.395994    0.844292    8.543430    1.933934
... 1   0.311974    9.519054    6.171577    3.859993
... 2   2.056797    0.836150    5.270513    3.224497
... 3   3.919300    8.562298    6.852941    1.415992
... 4   9.958550    9.013425    8.703142    3.588733
>>> float_col = df.select_dtypes(include=['float64']) # This will select float columns only
>>> # list(float_col.columns.values)
>>> for col in float_col.columns.values:
...     df[col] = df[col].astype('int64')
>>> print(df)
...     P   Q   R   S
... 0   4   0   8   1
... 1   0   9   6   3
... 2   2   0   5   3
... 3   3   8   6   1
... 4   9   9   8   3次の簡単な関数は、フロートを、情報を失わない最小の整数型にダウンキャストします。たとえば、
100.0は浮動小数点から整数に変換できますが、99.9は変換できません(丸めや切り捨てによって情報が失われることはありません)
さらに、1.0はint8情報を失うことなくずっとダウンキャストできますが、100_000.0の最小の整数型はint32
コード例:
import numpy as np
import pandas as pd
def float_to_int( s ):
    if ( s.astype(np.int64) == s ).all():
        return pd.to_numeric( s, downcast='integer' )
    else:
        return s
# small integers are downcast into 8-bit integers
float_to_int( np.array([1.0,2.0]) )
Out[1]:array([1, 2], dtype=int8)
# larger integers are downcast into larger integer types
float_to_int( np.array([100_000.,200_000.]) )
Out[2]: array([100000, 200000], dtype=int32)
# if there are values to the right of the decimal
# point, no conversion is made
float_to_int( np.array([1.1,2.2]) )
Out[3]: array([ 1.1,  2.2])
df.col = df.col.astype(int)