,python,pandas,csv,error-handling,time-series"/>

首页 > 解决方案 > Python- TypeError:无法将系列转换为

问题描述

我正在编写此代码以转换特定 csv 文件中的列,然后将其转换为人类可读的时间。但是,只有当我指定一个数据值并且当我尝试转换整个列时它才会显示此错误:TypeError: cannot convert the series to <class 'int'>

import pandas as pd 
from tkinter.filedialog import askopenfilename
import csv
from datetime import datetime, timedelta
n=0
file_path= askopenfilename(filetypes=(("CSV File","*.csv"),("All files","*.*")))
print(file_path)
selected_File = pd.read_csv(file_path)
print(selected_File.iloc[:,0])
dtime=datetime.fromtimestamp(selected_File.iloc[:,0])
print(type(dtime))
initial_date="1/1/1900 0:00:00"
i_date= datetime.strptime(initial_date,"%m/%d/%Y %H:%M:%S")
correct_date=i_date+timedelta(days=selected_File.iloc[:,0])
print(correct_date) 

标签: pythonpandascsverror-handlingtime-series

解决方案


您正在调用 Python 标准库函数datetime.fromtimestamp,它需要一个整数或类似的东西。您正在传递来自 Pandas 的系列,它不知道如何处理。

如果要对系列中的每个元素应用函数,则需要使用该Series.apply方法。例如,

selected_File.iloc[0,:].apply(datetime.fromtimestamp)

这是假设数据中的每一列都包含表示时间戳的整数。


推荐阅读