任務描述我想根據列(國家/地區)中的字符串合并數據幀列表,然后將其轉換為字典,并將國家/地區列作為鍵,將合并的數據幀作為值。數據示例:國家名稱列表country_names = ['ITA', USA', 'UK', 'ARG']名為 df_countries 的數據幀列表df_countries[0] index Date A B C Country 1 2019-12-31 x y z ITA 2 2019-12-30 x y z ITA df_countries[1] index Date A B C Country 1 2019-12-31 x y z ITA 2 2019-12-30 x y z ITA df_countries[2] index Date A B C Country 1 2019-12-31 x y z USA 2 2019-12-30 x y z USA df_countries[3] index Date A B C Country 1 2019-12-31 x y z ARG 2 2019-12-30 x y z ARG 例如,我希望ITA在合并后看起來像下面這樣,然后從中創建一個以ITA為鍵的字典等: index Date A B C Country 1 2019-12-31 x y z ITA 2 2019-12-30 x y z ITA 3 2019-12-31 x y z ITA 4 2019-12-30 x y z ITA 任何幫助都會超級棒!
1 回答

慕田峪4524236
TA貢獻1875條經驗 獲得超5個贊
從我的評論中詳細闡述了一下:您可以首先將所有數據幀與 合并,然后選擇匹配的行并從中創建新的數據幀:pd.concat()
merged_frame = pd.concat(df_countries)
country_dict = {}
for country in country_names:
country_dict[country] = merged_frame[merged_frame['Country'] == country]
(可選)您還可以調用來修復新幀的索引。country_dict[country].reset_index()
添加回答
舉報
0/150
提交
取消