python - 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)
解决方案
您正在调用 Python 标准库函数datetime.fromtimestamp
,它需要一个整数或类似的东西。您正在传递来自 Pandas 的系列,它不知道如何处理。
如果要对系列中的每个元素应用函数,则需要使用该Series.apply
方法。例如,
selected_File.iloc[0,:].apply(datetime.fromtimestamp)
这是假设数据中的每一列都包含表示时间戳的整数。
推荐阅读
- python - Dash Daq 温度计/仪表/LED 显示屏的颜色变化
- excel - VBA 编译错误:将 Excel 保存为 PDF for Excel 2019 的语法错误
- c# - 使用 HttpClient 和 HttpRequestMessage 的并发问题
- javascript - 显示 x 轴线但隐藏所有数据点
- javascript - Javascript this 关键字在 addEventListener 引用的函数中不起作用
- pandas - 像线图python一样可视化countplot
- javascript - 如何使用 Emotion 更改 react-bootstrap 的开关(Forms 组件的一部分)的背景颜色
- javascript - 输入字段保持先前输入的相同信息
- python - 给定分布方程,在 python 中生成数据集
- java - 如何在没有 java 外部类的情况下将 protobuf 消息用作 java 类?