微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

面临将字典中的数据添加到数据帧的问题

如何解决面临将字典中的数据添加到数据帧的问题

在创建将响应存储在列中的函数时遇到问题, 就像传递城市名称一样,作为响应获取 max_temp、min_temp、压力的详细信息。我想将其存储在新列中。

import pyowm
from pyowm.utils import config
from pyowm.utils import timestamps

api_key = {key from openweather(free)}
mgr = owm.weather_manager()
data =[]
def get_weather(city):
    observation = mgr.weather_at_place(city)
    l = observation.weather
    Wind_Speed = l.wind()['speed']
    Temp = l.temperature('celsius')['temp']
    Max_temp = l.temperature('celsius')['temp_max']
    Min_temp = l.temperature('celsius')['temp_min']
    #Heat_index = l.heat_index
    Humidity = l.humidity
    Pressure = l.pressure['press']
    weather = {"City": city,"Wind_Speed" : Wind_Speed,"Temp": 
    Temp,"Max_temp":Max_temp,"Min_temp":Min_temp,"Humidity":Humidity,"Pressure":Pressure}
    
    return weather

for city in df2['City']:
    get_weather(city)
    df = df.append(data,True)

想要根据城市名称将每个天气详细信息添加为列

想要创建一个将所有详细信息存储在列中的函数, 不想创建单独的函数

数据框就像:

enter image description here

解决方法

你可以从你的函数中返回一个字典。

df['Date'] = pd.to_datetime(df['Date'])

g = df['Date'].notna().groupby(df['Student_id']).cumsum()
add = pd.to_timedelta(df.groupby([g,'Student_id']).cumcount().mul(4),unit='D')

df['Date'] = df.groupby('Student_id')['Date'].ffill().add(add)
print (df)
        Date  Student_id    subject  Subject_Scores
0 2020-11-30     1000101       Math              70
1 2020-12-04     1000101    Physics              75
2 2020-12-08     1000101    Biology              60
3 2020-11-25     1000101  Chemistry              49
4 2020-11-29     1000101    English              80
5 2020-12-02     1000101  Sociology              50
6 2020-11-25     1000102    Physics              80
7 2020-11-29     1000102       Math              90
8 2020-12-15     1000102  Chemistry              63
9        NaT     1000103    English              71

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。