2017-09-11 14 views
2

特殊文字を含む列名を変換のような:Pythonのパンダのオブジェクトは、私はパンダのデータフレームが構造化してい

>>> df 
    Col1 Col.With.Dots Col.With.# Col.With.% 
0 text   111   111   111 
1 text   222   222   222 
2 text   333   333   333 
3 text   444   444   444 
4 text   555   555   555 

itertuples()でそれを反復、特殊文字ブレークの列:

>>> for i in df.itertuples(): 
... print i 

Pandas(Index=0, Col1='text', _2=111, _3=111, _4=111) 
Pandas(Index=1, Col1='text', _2=222, _3=222, _4=222) 
Pandas(Index=2, Col1='text', _2=333, _3=333, _4=333) 
Pandas(Index=3, Col1='text', _2=444, _3=444, _4=444) 
Pandas(Index=4, Col1='text', _2=555, _3=555, _4=555) 

"_2"、 "_3"、 "_4"はそれぞれ印刷出力の "Col.With.Dots"、 "Col.With。#"、 "Col.With。%"でなければなりません。

データフレームオブジェクトを生のdictに変換する必要があります。ですから、すべてのパンダオブジェクトは次のようなdictに変更されます: {'Col1': 'text', 'Col.With.Dots': 111, 'Col.With.#': 111, 'Col.With.%': 111 }

これを克服する方法はありますか?私はいくつかの研究を行なったし、答え

+2

df.iterrows()を使用を見つけることができなかった、彼らは_fixed_です。 'Col.With.Dots'などは有効なPython識別子ではありません。パンダは彼らを避けるために最善を尽くしています。 – DyZ

+0

@DYZ私はそれを理解していますが、この構造体を生のdictに変換する必要があります – Vinny

+0

なぜ列の名前を変更しないのですか? – Asterisk

答えて

1

使用to_dict()

In [1659]: df.to_dict('r') 
Out[1659]: 
[{'Col.With.#': 111L, 'Col.With.%': 111L, 'Col.With.Dots': 111L, 'Col1': 'text'}, 
{'Col.With.#': 222L, 'Col.With.%': 222L, 'Col.With.Dots': 222L, 'Col1': 'text'}, 
{'Col.With.#': 333L, 'Col.With.%': 333L, 'Col.With.Dots': 333L, 'Col1': 'text'}, 
{'Col.With.#': 444L, 'Col.With.%': 444L, 'Col.With.Dots': 444L, 'Col1': 'text'}, 
{'Col.With.#': 555L, 'Col.With.%': 555L, 'Col.With.Dots': 555L, 'Col1': 'text'}] 

または、ループのために、彼らは_broken_されていないto_dict()

In [1667]: for i, x in df.iterrows(): 
     ...:  print x.to_dict() 
     ...: 
{'Col.With.%': 111L, 'Col.With.Dots': 111L, 'Col.With.#': 111L, 'Col1': 'text'} 
{'Col.With.%': 222L, 'Col.With.Dots': 222L, 'Col.With.#': 222L, 'Col1': 'text'} 
{'Col.With.%': 333L, 'Col.With.Dots': 333L, 'Col.With.#': 333L, 'Col1': 'text'} 
{'Col.With.%': 444L, 'Col.With.Dots': 444L, 'Col.With.#': 444L, 'Col1': 'text'} 
{'Col.With.%': 555L, 'Col.With.Dots': 555L, 'Col.With.#': 555L, 'Col1': 'text'} 
+0

これは素晴らしいことです。 btw - 変換する前に値をfloatからintに変更する方法はありますか? – Vinny

関連する問題