我无法复制您的问题。这对我来说似乎很好用:
import pandas as pd
df = pd.DataFrame({'Floats': [10.1, 20.2, 30.3, 20.0, 15.9, 30.1, 45.0],
'Integers': [10.0, 20.0, 30, 20, 15, 30, 45]})
filename = 'df.xlsx'
writer = pd.ExcelWriter(filename)
df.to_excel(writer)
writer.save()
df = pd.read_excel(filename, convert_float=True)
print df
结果:
Floats Integers
0 10.1 10
1 20.2 20
2 30.3 30
3 20.0 20
4 15.9 15
5 30.1 30
6 45.0 45
运行此代码时是否得到相同的结果?如果是这样,那么肯定还有其他事情发生。你能给我们演示这个问题的代码吗?
请注意,每一列中至少有一个浮点数将使整列被视为浮点数,因为在给定的列中通常不能有多个数据类型(请参阅下面的object 列类型)。
如果上述代码由于某种原因不起作用,一种解决方法是手动强制某些列和/或索引为整数,如下所示:
df = pd.read_excel(filename) # convert_float=False by default
df['Integers'] = df['Integers'].astype(int)
df.index = df.index.astype(int)
print df
你可以强制所有列都是这样的整数:
df = pd.read_excel(filename).astype(int)
在 OP 给出更多细节后编辑:
如果您知道哪些列需要被视为字符串,则可以使用与上面相同的手动技术:
df['Strings'] = df['Strings'].astype(str)
但您希望它更加自动化。这是hacky,但它有效。如果您在数据的末尾添加一个明显是字符串的虚拟字符串,例如'dummy',那么 pandas 会将列作为对象引入,每个元素都有自己的数据类型。没有虚拟字符串,它不起作用。你可以试试我代码中注释掉的数据框看看。
import pandas as pd
# This works.
df = pd.DataFrame({'Floats': [10.1, 20.2, 30.3, 20.0, 15.9, 30.1, 0],
'Objects': ['10.0', 20.0, 30.5, 20, 15, 30, 'dummy']})
# This doesn't work.
# df = pd.DataFrame({'Floats': [10.1, 20.2, 30.3, 20.0, 15.9, 30.1],
# 'Objects': ['10.0', 20.0, 30.5, 20, 15, 30]})
filename = 'df.xlsx'
writer = pd.ExcelWriter(filename)
df.to_excel(writer)
writer.save()
# Remove the dummy row.
df = pd.read_excel(filename)[:-1]
print df
print
print df.dtypes
print
print df.loc[0, 'Objects'], type(df.loc[0, 'Objects'])
print df.loc[1, 'Objects'], type(df.loc[1, 'Objects'])
print df.loc[2, 'Objects'], type(df.loc[2, 'Objects'])
print df.loc[3, 'Objects'], type(df.loc[3, 'Objects'])
结果:
Floats Objects
0 10.1 10.0
1 20.2 20
2 30.3 30.5
3 20.0 20
4 15.9 15
5 30.1 30
Floats float64
Objects object
dtype: object
10.0 <type 'unicode'>
20 <type 'int'>
30.5 <type 'float'>
20 <type 'int'>