亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用兩個 Pandas 數據框創建列表列表

使用兩個 Pandas 數據框創建列表列表

翻翻過去那場雪 2023-03-08 16:34:30
我有這兩個數據框:1)這里的數據按 station_id(從 1 到 98)和時間(從 27-01-2020 到 26-05-2020 每小時的數據)分組在第二個數據框中,我有每個 station_id 的緯度和經度值。我的目標是以這種格式創建一個列表列表:     latitude           longitude      flow   hour  month  day[[53.37947845458979, -1.46990168094635, 278.0, 0.0, 1.0, 27.0],  [53.379791259765604, -1.46999669075012, 122.0, 0.0, 1.0, 27.0],  [53.380035400390604, -1.47001004219055, 58.0, 0.0, 1.0, 27.0], ...]為了讓第一個數據框中的每一行都有一個列表 [latitude, longitude, flow, month, day]。我嘗試使用以下代碼:import pandas as pdimport datetime as dtdf = pd.read_csv("readings_by_hour.csv")df['time'] = pd.to_datetime(df['time'])df1 = pd.read_csv("stations_info.csv")i = 0a = []b = []count = df1['station_id'].count()while i < count:    if df['station_id'][i] == df1['station_id'][i]:        a = print(df1['latitude'][i] + ", " + df1['longitude'][i] + ", " + df['flow'][i] + ", " + df['time'].dt.hour + ", " + df['time'].dt.month + ", " + df['time'].dt.day)        b += [a]        i += 1print(b)但它似乎不起作用,盡管它沒有給出任何錯誤,但確實沒有給出任何輸出。
查看完整描述

2 回答

?
揚帆大魚

TA貢獻1799條經驗 獲得超9個贊

您可以合并列上的兩個數據框station_id,然后像這樣創建列表列表:


merged_df = pd.merge(df, df1, left_on = 'station_id', right_on = 'station_id')


list_of_lists =[] 

  

# Iterate over each row 

for index, row in merged_df.iterrows():


    # Create list for the current row 

    rowlist =[row.latitude, row.longitude, row.flow, row.hour, row.month, row.day] 

      

    # append the list to the final list 

    list_of_lists.append(rowlist) 

您可以使用該模塊從列datetime中提取月、日、小時Date


pd.merge有關更多信息,請參閱 pandas 文檔: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html


查看完整回答
反對 回復 2023-03-08
?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

在給定的代碼中,您試圖將 print 函數的返回值分配給a,然后將其添加到b. a在這里,的值為null。因此,當您嘗試打印該值時,您將得到空字符串。


我已經進行了更正以使其有效。希望能幫助到你..


while i < count:

    if df['station_id'][i] == df1['station_id'][i]:

        a = [df1['latitude'][i],df1['longitude'][i], df['flow'][i], df['time'][i].hour,df['time'][i].month,df['time'][i].day]

        b.append(a)

        i += 1


print(b)


查看完整回答
反對 回復 2023-03-08
  • 2 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號