python - 读取文件时使用 lambda 函数将日期转换为时间戳

标签 python csv pandas lambda timestamp

我正在读取包含以下格式日期的 csv 文件:

date
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014

我不能以字符串格式使用这样的日期,我需要将其转换为数字时间戳。

所以我写了这段代码:

Train = pd.read_csv("train.tsv", sep='\t') 
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())

这给了我:

Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
AttributeError: 'Timestamp' object has no attribute 'timestamp'

您能否纠正我以获取 lambda 中的时间戳?

编辑代码:

Train = pd.read_csv("data_scientist_assignment.tsv", sep='\t', parse_dates=['date'])
#print df.head()
# Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
Train['timestamp'] = Train.date.values.astype(np.int64)
x1=["timestamp", "hr_of_day"]
test=pd.read_csv("test.csv")
print(Train.columns)
print(test.columns)
model = LogisticRegression()
model.fit(Train[x1], Train["vals"])
print(model)
print model.score(Train[x1], Train["vals"])

最佳答案

您需要将参数parse_dates添加到read_csv列名转换为日期时间:

import pandas as pd
import io

temp=u"""date
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep='\t', parse_dates=['date'])

print (df)
        date
0 2014-01-05
1 2014-01-05
2 2014-01-05
3 2014-01-05
4 2014-01-05
5 2014-01-05
6 2014-01-05
7 2014-01-05
8 2014-01-05

print (df.dtypes)
date    datetime64[ns]
dtype: object

另一个解决方案是为列 date 的顺序添加数字 - 在示例中它是第一列,因此添加 0 (python 从 0 开始计数) ):

df = pd.read_csv(io.StringIO(temp), sep='\t', parse_dates=[0])

print (df)
        date
0 2014-01-05
1 2014-01-05
2 2014-01-05
3 2014-01-05
4 2014-01-05
5 2014-01-05
6 2014-01-05
7 2014-01-05
8 2014-01-05

print (df.dtypes)
date    datetime64[ns]
dtype: object

然后需要通过 values 将列转换为 numpy 数组并转换为int:

#unix time in ns
df.date = df.date.values.astype(np.int64)
print (df)
                  date
0  1388880000000000000
1  1388880000000000000
2  1388880000000000000
3  1388880000000000000
4  1388880000000000000
5  1388880000000000000
6  1388880000000000000
7  1388880000000000000
8  1388880000000000000

#unix time in us
df.date = df.date.values.astype(np.int64) // 1000
print (df)
               date
0  1388880000000000
1  1388880000000000
2  1388880000000000
3  1388880000000000
4  1388880000000000
5  1388880000000000
6  1388880000000000
7  1388880000000000
8  1388880000000000
#unix time in ms
df.date = df.date.values.astype(np.int64) // 1000000
#df.date = pd.to_datetime(df.date, unit='ms')
print (df)
            date
0  1388880000000
1  1388880000000
2  1388880000000
3  1388880000000
4  1388880000000
5  1388880000000
6  1388880000000
7  1388880000000
8  1388880000000

#unix time in s
df.date = df.date.values.astype(np.int64) // 1000000000
print (df)
         date
0  1388880000
1  1388880000
2  1388880000
3  1388880000
4  1388880000
5  1388880000
6  1388880000
7  1388880000
8  1388880000

关于python - 读取文件时使用 lambda 函数将日期转换为时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39443887/

相关文章:

python - 如何知道reportlab PDF 页面是否已满?

javascript - 通过 Ajax 加载 CSV 数据以在 Highcharts 中显示

python - 在满足某些条件的情况下(在 Python 中)遍历 DataFrame 并计算 DataFrame 中出现次数的最快方法是什么?

Python - Spyder 在使用 Pandas DataFrame 时挂起

python - Flask 基本身份验证不接受用户名和密码

python - Django 管理员类型错误 : __init__() got an unexpected keyword argument 'allow_abbrev'

python - for循环在 Pandas 中使用iterrows

php - FPUTCSV 用 for 循环放置一个数组

python - 从 CSV 表创建 User-PageView 矩阵

python - Pandas 中的列名称 (Python)