python - TypeError:__init__() 为参数“索引”获取了多个值
问题描述
我正在尝试在 Python 中创建一个 DataFrame,以便我的索引是日期和时间值,并且我有两个对应的列,它们看起来像:
我在用:
import numpy as np
import pandas as pd
from pandas import DataFrame
import datetime
x = [0.03454225 0.02062136 0.00186715 0.01517354 0.0129046 0.02231125
0.01492537 0.09646542 0.28444476]
y = [2.25226244 1.44078451 0.99174488 0.71179491 0.92824542 1.67776948
2.96399534 5.06257161 7.06504245]
Date = 2012-01-01 01:00:00 ,2012-01-01 02:00:00, 2012-01-01 03:00:00,2012-01-01 04:00:00,2012-01-01 05:00:00,2012-01-01 06:00:00,2012-01-01 07:00:00,2012-01-01 08:00:00,2012-01-01 09:00:00, 2012-01-01 10:00:00
df = pd.DataFrame(DateTime, x,y ,columns=['Date','X','y'])
print (df )
我的数据的形状是:
> x.shape = (9,) , y.shape = (9,)
但Date.shape
显示错误AttributeError: 'list' object has no attribute 'shape'
将其放入数据框中的帮助将不胜感激
解决方案
import numpy as np
import pandas as pd
from pandas import DataFrame
from datetime import datetime, date, time
#added first element as 0 since there was column mismatch with x,y and Date in the code snippet in the question
x = [0, 0.03454225, 0.02062136, 0.00186715, 0.01517354, 0.0129046, 0.02231125, 0.01492537, 0.09646542, 0.28444476]
y = [0, 2.25226244, 1.44078451, 0.99174488, 0.71179491, 0.92824542, 1.67776948, 2.96399534, 5.06257161, 7.06504245]
#pass as string
Date = ['2012-01-01 01:00:00' ,'2012-01-01 02:00:00', '2012-01-01 03:00:00', '2012-01-01 04:00:00', '2012-01-01 05:00:00', '2012-01-01 06:00:00', '2012-01-01 07:00:00', '2012-01-01 08:00:00', '2012-01-01 09:00:00', '2012-01-01 10:00:00']
#convert string to datetime using list comprehension
dates=[datetime.strptime(x,'%Y-%m-%d %H:%M:%S') for x in Date]
#convert lists to dataframes with column names
df = pd.DataFrame({'date':dates,
'X':x,
'Y':y})
print (df)
推荐阅读
- testing - how to open pdf file in selenium webdriver c#
- xml - Requests from XMLDom to retrieve XML from API are blocked
- android - get data from Navigation Activity in Navigation library
- vba - 如何自动将数据条目从一个工作簿复制到另一个工作簿,而无需激活宏或打开工作簿
- reactjs - how can I hide an svg element with reactjs
- jbpm - How to fetch UserTask completionTime in JBPM
- python - IndexError 元组索引超出范围
- postgresql - 使用动态 SQL 在列表中创建对象
- qemu - 创建后备文件后libvirt“权限被拒绝”
- sql - MongoDB中的子查询