如何在Python中将dataframe转换为字符串

2024-10-01 00:29:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我们正在开发一个python项目,在这个项目中,我们使用SQLalchemyMySQL数据库中检索数据。我们成功地建立了与数据库的连接:

engine = create_engine("mysql://xxx:xxx@localhost/xxx")
conn = engine.connect()

当我们连接时,我们正在检索第一个和最后一个时间戳,因此我们可以设置一个范围和20分钟的间隔。我们使用以下代码行来实现这一点:

lastLpnTime = pd.read_sql('SELECT MAX(timestamp) FROM Raw_Data WHERE topic = "lpn1"', conn).astype(str).values
firstLpnTime = pd.read_sql('SELECT MIN(timestamp) FROM Raw_Data WHERE topic = "lpn1"', conn).astype(str).values.tolist()

然后,我们要将timestamp四舍五入为firstLpnTime,因此分钟将四舍五入为xx.00、xx.20、xx:40,例如15:09:25将四舍五入为15:00:00

firstLpnTime = pd.to_datetime(firstLpnTime).round('20T')

然后我们在firstLpnTimelastLpnTime之间设置一个范围,间隔20分钟

index = pd.date_range(start=firstLpnTime.min(), end=lastLpnTime.max(), freq='20T')

然而。。。我们收到这行代码的错误:

firstLpnTime = pd.to_datetime(firstLpnTime).round('20T')

错误消息是:

TypeError: arg must be a string, datetime, list, tuple, 1-d array, or Series

变量firstLpnTime有一个astype(str),所以它应该是一个字符串,所以我们不明白为什么它不工作。可能数据类型没有变为字符串?你知道吗

当我打印firstLpnTime时,输出是:[['2019-07-26 15:09:25']]


Tags: 项目代码数据库readdatetime间隔connengine
2条回答

为了避免值嵌套在数组中,您可以直接使用数据帧,如下代码所示:

import pandas as pd
from sqlalchemy import create_engine

engine = create_engine('mysql://xxxx:xxxx@localhost:3306/test')
conn = engine.connect()

lastLpnTime = pd.read_sql('SELECT MAX(timestamp) as max_time FROM 
     test.test_table WHERE topic = "lpn1";', conn).iloc[0]['max_time']
firstLpnTime = pd.read_sql('SELECT MIN(timestamp) as min_time FROM 
     test.test_table WHERE topic = "lpn1"', conn).iloc[0]['min_time']

firstLpnTime = firstLpnTime.round('20T')
firstLpnTime

这将在时间戳类中提供预期的输出。你知道吗

Timestamp('2019-07-26 15:00:00')

希望有帮助!:)

看起来您的firstLpnTime嵌套在一个数组中。你知道吗

因此,您可以尝试从这个变量中获取第一个索引,然后使用pandas进行强制转换。你知道吗

firstLpnTime = pd.to_datetime(firstLpnTime[0]).round('20T')

那么,firstLpnTime应该给出这个结果:

DatetimeIndex(['2019-07-26 15:00:00'], dtype='datetime64[ns]', freq=None)

我希望它能解决你的问题。你知道吗

相关问题 更多 >