Python:使用子列表将特定值从多个列表记录到单个数据帧

Python:使用子列表将特定值从多个列表记录到单个数据帧,python,pandas,dataframe,Python,Pandas,Dataframe,我正试图将气象站的特定数据保存到数据帧中。我的代码以子列表的形式检索每小时日志数据,并简单地放入pd.DataFrame由于多个日志和子列表而无法工作 我试图制作一个代码,用于检索每个小时日志条目的特定参数,例如temphhigh,并将其放入数据帧中。 我能够通过以下方式在第一个小时内隔离“tempHigh”: df = wu.hourly()["observations"][0] x = df["metric"] x["tempHigh&quo

我正试图将气象站的特定数据保存到数据帧中。我的代码以子列表的形式检索每小时日志数据,并简单地放入
pd.DataFrame
由于多个日志和子列表而无法工作

我试图制作一个代码,用于检索每个小时日志条目的特定参数,例如
temphhigh
,并将其放入数据帧中。 我能够通过以下方式在第一个小时内隔离“tempHigh”:

df = wu.hourly()["observations"][0]
x = df["metric"]
x["tempHigh"]
恐怕我得对付我的死敌福尔·洛普先生,检索每小时的日志数据。我希望在如何最有效地解决这个问题上得到一些帮助

屏幕截图显示了输出数据结构,该结构在过去7天的所有时间内都在继续。下面我粘贴了前两个日志条目的输出数据


Pandas接受字典列表作为输入,以创建:

如果您现在想要一个单一“指标”列表,则需要“展平”字典列表列。这确实使用了你的“复仇女神”,但以一种类似蟒蛇的方式:

temperature_high = [d.get("tempHigh") for d in df["metric"].to_list()]
如果您希望在一个数据框架中包含所有度量,甚至更简单,只需从特定列中获取字典列表:

metrics = pd.DataFrame(df["metric"].to_list())
由于您可能希望时间戳作为表示条目(行)的索引,因此可以选择列
历元
,或更人性化的
obtimelocal

metrics = pd.DataFrame(df["metric"].to_list(), index=df["obsTimeLocal"].to_list())
从这里,您可以阅读您感兴趣的具体指标:

metrics[["tempHigh", "tempLow"]]

熊猫接受字典列表作为输入,以创建:

如果您现在想要一个单一“指标”列表,则需要“展平”字典列表列。这确实使用了你的“复仇女神”,但以一种类似蟒蛇的方式:

temperature_high = [d.get("tempHigh") for d in df["metric"].to_list()]
如果您希望在一个数据框架中包含所有度量,甚至更简单,只需从特定列中获取字典列表:

metrics = pd.DataFrame(df["metric"].to_list())
由于您可能希望时间戳作为表示条目(行)的索引,因此可以选择列
历元
,或更人性化的
obtimelocal

metrics = pd.DataFrame(df["metric"].to_list(), index=df["obsTimeLocal"].to_list())
从这里,您可以阅读您感兴趣的具体指标:

metrics[["tempHigh", "tempLow"]]

我可能会有一个适合你的解决方案。我解决这个问题的方法是将单个小时日志的条目展平,这样就不会有嵌套字典。使用一维字典(每小时一个),可以轻松地创建一个数据框架,其中所有度量值都作为列,日期和时间作为索引。从这里开始,您可以选择您想要的任何列;)

我们如何到达那里?我所说的“展平条目”是什么意思

每小时日志都是带有单个键、值对的单个字典,而“metric”是另一个字典。我想要的是去掉键“metric”,而不是它的值。让我们看一个例子:

# nested dictionary
original = {'a':1, 'b':2, 'foo':{'c':3}} 

# flatten original to
flattened = {'a':1, 'b':2, 'c':3} # got rid of key 'foo' but not its value
下面的函数正好实现了一维或平面字典:

def flatten(dic):
    #
    update = False
    
    for key, val in dic.items():
        if isinstance(val, dict):
            update = True
            break
    
    if update: dic.update(val); dic.pop(key); flatten(dic)
    
    return dic

# With data from your weather station
hourly_log = {'epoch': 1607554798, 'humidityAvg': 39, 'humidityHigh': 44, 'humidityLow': 37, 'lat': 27.389829, 'lon': 33.67048, 'metric': {'dewptAvg': 4, 'dewptHigh': 5, 'dewptLow': 4, 'heatindexAvg': 19, 'heatindexHigh': 19, 'heatindexLow': 18, 'precipRate': 0.0, 'precipTotal': 0.0, 'pressureMax': 1017.03, 'pressureMin': 1016.53, 'pressureTrend': 0.0, 'tempAvg': 19, 'tempHigh': 19, 'tempLow': 18, 'windchillAvg': 19, 'windchillHigh': 19, 'windchillLow': 18, 'windgustAvg': 8, 'windgustHigh': 13, 'windgustLow': 2, 'windspeedAvg': 6, 'windspeedHigh': 10, 'windspeedLow': 2}, 'obsTimeLocal': '2020-12-10 00:59:58', 'obsTimeUtc': '2020-12-09T22:59:58Z', 'qcStatus': -1, 'solarRadiationHigh': 0.0, 'stationID': 'IHURGH2', 'tz': 'Africa/Cairo', 'uvHigh': 0.0, 'winddirAvg': 324}
# Flatten with function
flatten(hourly_log)
>>> {'epoch': 1607554798,
     'humidityAvg': 39,
     'humidityHigh': 44,
     'humidityLow': 37,
     'lat': 27.389829,
     'lon': 33.67048,
     'obsTimeLocal': '2020-12-10 00:59:58',
     'obsTimeUtc': '2020-12-09T22:59:58Z',
     'qcStatus': -1,
     'solarRadiationHigh': 0.0,
     'stationID': 'IHURGH2',
     'tz': 'Africa/Cairo',
     'uvHigh': 0.0,
     'winddirAvg': 324,
     'dewptAvg': 4,
     'dewptHigh': 5,
     'dewptLow': 4,
     'heatindexAvg': 19,
     'heatindexHigh': 19,
     'heatindexLow': 18,
     'precipRate': 0.0,
     'precipTotal': 0.0,
     'pressureMax': 1017.03,
     'pressureMin': 1016.53,
     'pressureTrend': 0.0, 
      ...
注意:“metric”消失了,但它的值没有了

现在,可以很容易地为每个小时日志创建一个数据帧,该日志可以连接到单个数据帧:

import pandas as pd

hourly_logs = wu.hourly()['observations']

# List of DataFrames for each hour
frames = [pd.DataFrame(flatten(dic), index=[0]).set_index('epoch') for dic in hourly_logs]

# Concatenated to a single one
df = pd.concat(frames)

# With adjusted index as Date and Time
dti = pd.DatetimeIndex(df.index * 10**9)
df.index = pd.MultiIndex.from_arrays([dti.date, dti.time])

# All measures
df.columns
>>> Index(['humidityAvg', 'humidityHigh', 'humidityLow', 'lat', 'lon',
       'obsTimeLocal', 'obsTimeUtc', 'qcStatus', 'solarRadiationHigh',
       'stationID', 'tz', 'uvHigh', 'winddirAvg', 'dewptAvg', 'dewptHigh',
       'dewptLow', 'heatindexAvg', 'heatindexHigh', 'heatindexLow',
       'precipRate', 'precipTotal', 'pressureMax', 'pressureMin',
       'pressureTrend', 'tempAvg', 'tempHigh', 'tempLow', 'windchillAvg',
       'windchillHigh', 'windchillLow', 'windgustAvg', 'windgustHigh',
       'windgustLow', 'windspeedAvg', 'windspeedHigh', 'windspeedLow'],
      dtype='object')

# Read out specific measures
df[['tempHigh','tempLow','tempAvg']]
>>>


希望这就是你一直在寻找的

我可能有一个适合你的解决方案。我解决这个问题的方法是将单个小时日志的条目展平,这样就不会有嵌套字典。使用一维字典(每小时一个),可以轻松地创建一个数据框架,其中所有度量值都作为列,日期和时间作为索引。从这里开始,您可以选择您想要的任何列;)

我们如何到达那里?我所说的“展平条目”是什么意思

每小时日志都是带有单个键、值对的单个字典,而“metric”是另一个字典。我想要的是去掉键“metric”,而不是它的值。让我们看一个例子:

# nested dictionary
original = {'a':1, 'b':2, 'foo':{'c':3}} 

# flatten original to
flattened = {'a':1, 'b':2, 'c':3} # got rid of key 'foo' but not its value
下面的函数正好实现了一维或平面字典:

def flatten(dic):
    #
    update = False
    
    for key, val in dic.items():
        if isinstance(val, dict):
            update = True
            break
    
    if update: dic.update(val); dic.pop(key); flatten(dic)
    
    return dic

# With data from your weather station
hourly_log = {'epoch': 1607554798, 'humidityAvg': 39, 'humidityHigh': 44, 'humidityLow': 37, 'lat': 27.389829, 'lon': 33.67048, 'metric': {'dewptAvg': 4, 'dewptHigh': 5, 'dewptLow': 4, 'heatindexAvg': 19, 'heatindexHigh': 19, 'heatindexLow': 18, 'precipRate': 0.0, 'precipTotal': 0.0, 'pressureMax': 1017.03, 'pressureMin': 1016.53, 'pressureTrend': 0.0, 'tempAvg': 19, 'tempHigh': 19, 'tempLow': 18, 'windchillAvg': 19, 'windchillHigh': 19, 'windchillLow': 18, 'windgustAvg': 8, 'windgustHigh': 13, 'windgustLow': 2, 'windspeedAvg': 6, 'windspeedHigh': 10, 'windspeedLow': 2}, 'obsTimeLocal': '2020-12-10 00:59:58', 'obsTimeUtc': '2020-12-09T22:59:58Z', 'qcStatus': -1, 'solarRadiationHigh': 0.0, 'stationID': 'IHURGH2', 'tz': 'Africa/Cairo', 'uvHigh': 0.0, 'winddirAvg': 324}
# Flatten with function
flatten(hourly_log)
>>> {'epoch': 1607554798,
     'humidityAvg': 39,
     'humidityHigh': 44,
     'humidityLow': 37,
     'lat': 27.389829,
     'lon': 33.67048,
     'obsTimeLocal': '2020-12-10 00:59:58',
     'obsTimeUtc': '2020-12-09T22:59:58Z',
     'qcStatus': -1,
     'solarRadiationHigh': 0.0,
     'stationID': 'IHURGH2',
     'tz': 'Africa/Cairo',
     'uvHigh': 0.0,
     'winddirAvg': 324,
     'dewptAvg': 4,
     'dewptHigh': 5,
     'dewptLow': 4,
     'heatindexAvg': 19,
     'heatindexHigh': 19,
     'heatindexLow': 18,
     'precipRate': 0.0,
     'precipTotal': 0.0,
     'pressureMax': 1017.03,
     'pressureMin': 1016.53,
     'pressureTrend': 0.0, 
      ...
注意:“metric”消失了,但它的值没有了

现在,可以很容易地为每个小时日志创建一个数据帧,该日志可以连接到单个数据帧:

import pandas as pd

hourly_logs = wu.hourly()['observations']

# List of DataFrames for each hour
frames = [pd.DataFrame(flatten(dic), index=[0]).set_index('epoch') for dic in hourly_logs]

# Concatenated to a single one
df = pd.concat(frames)

# With adjusted index as Date and Time
dti = pd.DatetimeIndex(df.index * 10**9)
df.index = pd.MultiIndex.from_arrays([dti.date, dti.time])

# All measures
df.columns
>>> Index(['humidityAvg', 'humidityHigh', 'humidityLow', 'lat', 'lon',
       'obsTimeLocal', 'obsTimeUtc', 'qcStatus', 'solarRadiationHigh',
       'stationID', 'tz', 'uvHigh', 'winddirAvg', 'dewptAvg', 'dewptHigh',
       'dewptLow', 'heatindexAvg', 'heatindexHigh', 'heatindexLow',
       'precipRate', 'precipTotal', 'pressureMax', 'pressureMin',
       'pressureTrend', 'tempAvg', 'tempHigh', 'tempLow', 'windchillAvg',
       'windchillHigh', 'windchillLow', 'windgustAvg', 'windgustHigh',
       'windgustLow', 'windspeedAvg', 'windspeedHigh', 'windspeedLow'],
      dtype='object')

# Read out specific measures
df[['tempHigh','tempLow','tempAvg']]
>>>


希望这就是你一直在寻找的

数据示例中缺少一个
}]}
。数据示例中缺少一个
}]}