B列到K列的所有数据都是以文本形式存储在Excel文件中的数字。
我已将 excel 文件上传到 dropbox 作为测试样本。
sample data text
下载并保存在/tmp/tsm.xlsx
中。
我发现最后一个K列的数据类型是str,从B到J的列读入dataframe后都是数字类型:
import pandas as pd
sexcel = '/tmp/tsm.xlsx'
df = pd.read_excel(sexcel,sheet_name='ratios_annual')
row_num = len(df)
for id in range(row_num):
print('the data type in last column--K is',type(df.iloc[id,-1]))
print('the data type in column--J is',type(df.iloc[id,-2]))
the data type in last column--K is <class 'str'>
the data type in column--J is <class 'numpy.float64'>
the data type in last column--K is <class 'str'>
the data type in column--J is <class 'numpy.float64'>
很明显,在Excel中打开它时,从B列到K列都是存储为文本的数字
。为什么当我将其读入数据框时,类型不同?
请下载示例数据并检查。
最佳答案
我已通过 Dropbox 下载该文件并将其加载到具有以下版本的 pandas
环境中(从 conda-forge
安装):
- pandas=1.5.3
- openpyxl=3.1.0
原始问题中的代码片段执行正确,所有数据列都被标识为 float
。请检查您的 pandas
和 openpyxl
版本并升级(如果可行):
from pandas import __version__
print(__version__) # 1.5.3
from openpyxl import __version__
print(__version__) # 3.1.0
关于python - 为什么最后一列的数据类型是 str 而不是 float?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75425731/