【发布时间】:2019-08-13 23:48:44
【问题描述】:
我有两个数据框,我想做的是根据 Sensor_Type 创建新列并将它们添加到 DF1 并根据传感器分配每个测量值。
DF1:
Weather_Legends.head():
Sensor_ID Sensor_Street_Name Sensor_Lat Sensor_Long Sensor_Type UOM
0 6030 Milano - via Brera 45.471192 9.187616 Wind Direction degree
1 5897 Milano - via Brera 45.471192 9.187616 Temperature Celsius degree
2 6174 Milano - via Brera 45.471192 9.187616 Relative Humidity %
3 6120 Milano - via Brera 45.471192 9.187616 Wind Speed m/s
4 2006 Milano - via Lambrate 45.490051 9.22559 Precipitation mm
DF2:
Mi_Meteo.head():
Sensor_ID Time_Instant Measurement
0 14121 2013-11-01 01:00:00 0.8
1 14121 2013-11-01 02:00:00 0.6
2 14121 2013-11-01 03:00:00 0.4
3 14121 2013-11-01 04:00:00 0.4
4 14121 2013-11-01 05:00:00 0
这是所需的输出:
Sensor_Type Sensor_ID Sensor_Street_Name Time_Instant Precipitation Relative Humidity Wind Speed …..
0 14121 Milano - via Ippolito Rosellini 2013-11-01 01:00:00 0.8 NaN NaN
1 14121 Milano - via Ippolito Rosellin 2013-11-01 02:00:00 NaN 0.6 NaN
2 14121 Milano - via Ippolito Rosellini 2013-11-01 03:00:00 0.4 NaN NaN
.
.
.
相反,这些就是我得到的:
Sensor_Type Sensor_ID Sensor_Street_Name Time_Instant Precipitation
0 14121 Milano - via Ippolito Rosellini 2013-11-01 01:00:00 0.8
1 14121 Milano - via Ippolito Rosellini 2013-11-01 02:00:00 0.6
2 14121 Milano - via Ippolito Rosellini 2013-11-01 03:00:00 0.4
.
.
缺少其他传感器类型!!!
这是我使用的代码:
Mi_Meteo['Measurement'] = Mi_Meteo['Measurement'].str.rstrip(' Measure').str.strip()
Mi_Meteo['Measurement'] = pd.to_numeric(Mi_Meteo['Measurement'] ,errors='coerce' )
Mi_Meteo['Sensor_ID'] = Mi_Meteo['Sensor_ID'].str.rstrip(' ID').str.strip()
Mi_Meteo['Sensor_ID'] = pd.to_numeric(Mi_Meteo['Sensor_ID'] ,errors='coerce' )
Mi_Meteo['Measurement'] = Mi_Meteo['Measurement'].astype(float)
Mi_Meteo['Sensor_ID'] = Mi_Meteo['Sensor_ID'].astype(float)
df4 = Mi_Meteo.merge(Weather_Legends, on='Sensor_ID', how='left')\
.pivot_table(index=['Sensor_ID' ,'Sensor_Street_Name' , 'Time_Instant' ],
values= 'Measurement',
columns='Sensor_Type')\
.reset_index()
df4['Sensor_ID'] = df4['Sensor_ID'].astype(int)
任何建议都会非常感谢,谢谢大家。
【问题讨论】:
-
如果要保留两个键,请尝试使用外连接?
-
我已经尝试过 'outer' 是一样的
-
您熟悉 SQL 以及主键和外键吗?从前 2 个表来看,似乎每个 sensor_id 只进行一种类型的测量。但是,您的第三张表(所需的输出)显示每个 sensor_id 实际上都需要多种类型的测量。它是哪一个?您向我们展示的内容似乎存在很大的不一致
-
@Pythonistaanonymous,不幸的是,我没有 SQL 经验,但基本上我想要它做的是,每当它遇到 Senor_ID 时,它都会为它分配适当的 Sensor_Type,例如,每次它看到传感器 14121,它为它分配氨传感器类型,并用 Nan 填充其他传感器类型列。
-
你还没有回答我的问题。表的主键是什么,即每个表中哪些字段是唯一的,不重复的?查找主键和外键。它可以帮助您了解数据的结构。每个传感器 ID 是仅与一种传感器类型相关联,还是与多个传感器类型相关联?您可以上传您的一些数据供我们查看还是保密? PS 那么,米兰的污染程度如何? :)
标签: python-3.x pandas dataframe pivot-table multiple-columns