ナンシーは、 str
そして object
タイプ。例えば私はできる:
>>> import pandas as pd
>>> import numpy as np
>>> np.dtype(str)
dtype("S")
>>> np.dtype(object)
dtype("O")
ここで、dtype( "S")とdtype( "O")は str
そして object
それぞれ、
しかし、パンダにはその区別がないようです。 str
に object
。 ::
>>> df = pd.DataFrame({"a": np.arange(5)})
>>> df.a.dtype
dtype("int64")
>>> df.a.astype(str).dtype
dtype("O")
>>> df.a.astype(object).dtype
dtype("O")
強制的にタイプを dtype("S")
どちらも助けにならない。 ::
>>> df.a.astype(np.dtype(str)).dtype
dtype("O")
>>> df.a.astype(np.dtype("S")).dtype
dtype("O")
この動作の説明はありますか?
回答:
回答№1の13Numpyの文字列型はPythonの文字列ではありません。
このため、 pandas
意図的にオブジェクトdtypeを必要とするネイティブのPython文字列を使用します。
まず、numpyの文字列が違うということを少し説明しましょう。
In [1]: import numpy as np
In [2]: x = np.array(["Testing", "a", "string"], dtype="|S7")
In [3]: y = np.array(["Testing", "a", "string"], dtype=object)
今、「x」は numpy
文字列dtype(固定幅、cのような文字列)と y
ネイティブのPython文字列の配列です。
7文字を超えようとすると、すぐに違いが見られます。文字列dtypeのバージョンは切り捨てられます:
In [4]: x[1] = "a really really really long"
In [5]: x
Out[5]:
array(["Testing", "a reall", "string"],
dtype="|S7")
オブジェクトdtypeのバージョンは任意の長さにすることができます:
In [6]: y[1] = "a really really really long"
In [7]: y
Out[7]: array(["Testing", "a really really really long", "string"], dtype=object)
次に、 |S
dtype文字列はunicodeを適切に保持することはできませんが、Unicodeの固定長文字列dtypeもあります。ここでは例をスキップします。
最後に、numpyの文字列は実際には変更可能ですが、Python文字列は変更できません。
In [8]: z = x.view(np.uint8)
In [9]: z += 1
In [10]: x
Out[10]:
array(["Uftujoh", "b!sfbmm", "tusjohx01"],
dtype="|S7")
これらの理由のすべてについて、 pandas
Cのような固定長の文字列をデータ型として使用することをこれまで許可しませんでした。あなたが気づいたように、pythonの文字列をfixed-numpyの文字列に強制しようとすると、 pandas
。代わりに、常にネイティブのPython文字列を使用します。これは、ほとんどのユーザーにとってより直観的な方法で動作します。