【发布时间】:2022-01-03 17:55:20
【问题描述】:
我有这个数据集在:https://gitlab.com/creativitylabb/dataset-test/-/raw/main/final_pagination.csv 处理后数据看起来像这样:
TimeStamp Source Sensor Value LocationLat LocationLong Measurement
TimeStamp
01.02.2021 07:00:00 01.02.2021 07:00:00 Waqi pm10 16.0 45.716700 25.633300 µg/m3
01.02.2021 07:00:00 01.02.2021 07:00:00 Waqi no2 4.0 45.716700 25.633300 µg/m3
01.02.2021 07:00:00 01.02.2021 07:00:00 Waqi no2 2.3 45.716700 25.633300 µg/m3
01.02.2021 07:00:00 01.02.2021 07:00:00 Waqi o3 19.8 45.716700 25.633300 µg/m3
01.02.2021 08:00:00 01.02.2021 08:00:00 Waqi no2 28.5 45.659833 25.614488 µg/m3
我使用的处理方式:
from datetime import datetime
import pandas as pd
df = pd.read_csv('https://gitlab.com/creativitylabb/dataset-test/-/raw/main/final_pagination.csv')
df = df.drop(['id', 'index', 'type', 'score', 'Unnamed: 0'], 1)
df['TimeStamp'] = df['TimeStamp'].apply(lambda x: datetime.utcfromtimestamp(x / 1000).strftime('%d.%m.%Y %H:%M:%S'))
df = df.sort_values(by='TimeStamp').reset_index(drop=True)
print(df.head().to_string())
df.index = df['TimeStamp']
Sensor 值包含 pm10、pm2.5、co2 等传感器。值列包含传感器的测量值。如何将数据拆分为其他列,以便我可以有一个具有 pm10 值的列,另一个具有 pm2.5 值的列等等? (最好不要有所有其他列 Nan)
示例输出:
TimeStamp Source pm10 pm25 LocationLat LocationLong Measurement
TimeStamp
01.02.2021 07:00:00 01.02.2021 07:00:00 Waqi 16.0 20 45.716700 25.633300 µg/m3
01.02.2021 07:00:00 01.02.2021 07:00:00 Waqi 4.0 21 45.716700 25.633300 µg/m3
01.02.2021 07:00:00 01.02.2021 07:00:00 Waqi 2.3 20 45.716700 25.633300 µg/m3
01.02.2021 07:00:00 01.02.2021 07:00:00 Waqi 19.8 25 45.716700 25.633300 µg/m3
01.02.2021 08:00:00 01.02.2021 08:00:00 Waqi 28.5 24 45.659833 25.614488 µg/m3
【问题讨论】:
-
能否展示一个包含预期输出的示例数据框?
-
这能回答你的问题吗? How can I pivot a dataframe?
-
@richardec 我用示例输出更新了答案
-
@G.Anderson 但数据透视表为我提供了除一列之外的所有其他列的 NaN 值以及传感器值。有什么办法可以逃脱吗?
-
@IanKurtis 我有点困惑...在您的示例输出中,如果您保持其余行不变,那么当pm10 测量的数量与总行数不同?例如,在时间戳
01.02.2021 07:00:00期间只有一个pm10测量值,因此如果您在该时间戳期间为pm10创建一个新列,那么同一时间戳的其他行将用于列pm10?
标签: python pandas dataframe datetime