Skip to main content
 首页 » 编程设计

Python pandas对象将列名转换为特殊字符

2025年02月15日9Leo_wl

我有一个 pandas 数据框,其结构如下:

>>> 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.%”。

我需要将 dataframe 对象转换为 raw dict。所以每个 Pandas 对象都变成了这样的字典: {'Col1': 'text', 'Col.With.Dots': 111, 'Col.With.#': 111, 'Col.With.%': 111}

有没有办法克服这个问题?我做了一些研究,但找不到答案

请您参考如下方法:

使用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'}] 

或者,对于循环,使用 df.iterrows()使用 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'}