pandas.DataFrame
のコンストラクタを使用し、dtype
引数を使用することに問題があります。文字列の値を保持したいのですが、次のスニペットは常に数値型に変換してNaN
を返します。pandas.DataFrame文字列dtypeを設定する(ファイルベースではない)
from __future__ import unicode_literals
from __future__ import print_function
import numpy as np
import pandas as pd
def main():
columns = ['great', 'good', 'average', 'bad', 'horrible']
# minimal example, dates are coming (as strings) from some
# non-file source.
example_data = {
'alice': ['', '', '', '2016-05-24', ''],
'bob': ['', '2015-01-02', '', '', '2012-09-15'],
'eve': ['2011-12-31', '', '1998-08-13', '', ''],
}
# first pass, yields dataframe full of NaNs
df = pd.DataFrame(data=example_data, index=example_data.keys(),
columns=columns, dtype=str) #or string, 'str', 'string', 'object'
print(df.dtypes)
print(df)
print()
# based on https://github.com/pydata/pandas/blob/master/pandas/core/frame.py
# and https://github.com/pydata/pandas/blob/37f95cef85834207db0930e863341efb285e38a2/pandas/types/common.py
# we're ultimately feeding dtype to numpy's dtype, so let's just use that:
# (using np.dtype('S10') and converting to str doesn't work either)
df = pd.DataFrame(data=example_data, index=example_data.keys(),
columns=columns, dtype=np.dtype('U'))
print(df.dtypes)
print(df) # still full of NaNs... =(
if __name__ == '__main__':
main()
dtypes
の値は、データフレーム内の文字列を保持しますか?参照用
:
$ pythonの--version
2.7.12
$のPIP2リスト| grepのパンダ
パンダ(0.18.1)
$のPIP2リスト|グレップのnumpyの
numpyの(1.11.1)
これはうまくいきます。好奇心のために、オリジナルがそうではないのにこれがなぜ機能するのか知っていますか?普通のコンストラクタが辞書を取ることができるとすれば、なぜfrom_dictコンストラクタがどう振る舞うのかが分かりません。 – everial
@everial:それをもっと慎重に見て、あなたが間違っていたことを理解しました。編集を参照してください。 –
詳細なフォローアップをいただきありがとうございます...私はパンダの経験がどのようになっているかをご覧いただけます。 =) – everial