Python对象转换具有特殊字符的列名

Python对象转换具有特殊字符的列名,python,pandas,csv,special-characters,Python,Pandas,Csv,Special Characters,我有一个熊猫数据框架,其结构如下: >>> 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

我有一个熊猫数据框架,其结构如下:

>>> 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”应分别为“带点颜色”、“带点颜色”、“带点颜色”、“带百分比颜色”

我需要将数据帧对象转换为原始dict。因此,每个pandas对象都被更改为dict,例如:
{'Col1':'text','Col.With.Dots':111,'Col.With.#':111,'Col.With.%':111}

有没有办法克服这个问题?我做了一些调查,没有找到答案

或者,对于循环,与
一起使用to_dict()


它们不是坏的,而是固定的
Col.With.Dots
等不是有效的Python标识符。Pandas正在尽最大努力避免它们。@DYZ我明白这一点,但我需要将此结构转换为原始dict为什么不重命名列?@JohnGalt将数据帧转换为rawdict(dict列表),因此对于每个Pandas对象,我都会得到一个dict{'Col1':'text','Col.With.Dots':111,'Col.With.#':111…@Asterisk这是一个更大程序的一部分,我试图避免修改标题。使用
csv
模块可以很好地工作,但是当csv大小变大(500mb+)pandas成功加载文件时失败。这很好,谢谢。顺便问一下,有没有办法在转换之前将值从float更改为int?
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'}]
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'}