python - 如何将 DataFrame 的列名从字符串转换为整数

标签 python pandas dataframe

在下面的代码中,我将一个字符串读入 DataFrame,但即使输入字符串的 header 是数字,它们也会以字符串 '1', '2' 的形式读入。有没有办法将它们作为数字读取,或者随后将它们转换为数字?

import pandas as pd
from StringIO import StringIO


string_input = " 1 2\n10 0.1 0.2\n20 0.1 0.2"
data = pd.read_table(StringIO(string_input), sep='\s+')
print data
print data.columns

      1    2
10  0.1  0.2
20  0.1  0.2

Index([u'1', u'2'], dtype='object') # the columns names are of type str!!

最佳答案

您可以使用 astype(int) 作为后处理步骤来执行此操作:

In [86]:
string_input = " 1 2\n10 0.1 0.2\n20 0.1 0.2"
data = pd.read_table(io.StringIO(string_input), sep='\s+')
print (data)
print (data.columns.astype(int))
​
      1    2
10  0.1  0.2
20  0.1  0.2
Int64Index([1, 2], dtype='int64')

就我个人而言,我更喜欢字符串列,因为在阅读和编写代码时索引 IMO 时它变得不那么模糊,就像做 df['col_name'] 成为一种习惯,并且当你有一个默认的 int64 索引则 df.loc[some_int] 是明确的

关于python - 如何将 DataFrame 的列名从字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42559297/

相关文章:

python - Django 教程 1 - 导入错误 : No module named apps

python - 创建一个唯一的文件系统路径,没有任何实际文件

python - 在 Pandas 中删除特定行

python - 如何在抓取的 Pandas 数据框中的所有列上使用 `str.replace()` 方法?

r - 在 R 中创建 sumif 函数的等效项

python - 使用 Python 替换数据框中的值

python - Django - 属性错误: 'module' object has no attribute 'admin'

Python:Gmail 未读邮件崩溃

python - 如何在 Pandas 中拆分数据框

python - 有什么好的方法来探索Python数据类型吗?