簡體   English   中英

For 循環將 pandas dataframe 與常用列合並

[英]For loop to merge pandas dataframe with common columns

我有 25 個數據框,每個都有 7 個升序日期(作為行)和 570-600 個機場名稱作為列。 最大的問題是,由於數據框存儲了每個機場每天的提升次數,某些機場不活動的幾周會導致數據框具有不同的順序和數量,類似和不同的機場名稱。 All of the column names will appear in alphabetical order in each dataframe, but the absence of just one airport column from the dataframe messes up the entire alignment of the master dataframe.

我已經嘗試過合並、連接、加入、更新……這個問題真的很復雜,我的最終目標是擁有一個主 dataframe,所有現有的按字母順序排列的機場作為列,並且隨着日期的上升和時間的流逝而持續的行。

我想我必須做一個for循環才能做到這一點:1.不會丟失任何數據2.它需要按列合並數據幀,這樣如果第二個數據幀的列名與第一個數據幀的列相同,新數據將添加到該列下方,而無需再次重復列名。 3.如果第二個的列名與第一個的列名不同,我希望將該列添加為新列(希望按字母順序)。 4.如果第二個 dataframe 沒有第一個的列,我想讓它說那個機場的 NAN。

總之,我希望 for 循環做的主要部分是在相同的列下添加數據(即使數據框的列亂序),添加以前不存在的列,填寫機場缺失的 NAN,以及確保列名僅顯示為 0 行。 對不起,這很難解釋。

這是兩個簡單的 dataframe 示例,我希望 for 循環能夠合並

df1 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
                    columns=['Airport1', 'Airport3', 'Airport4'])
df1.index.name='Dates'
df1.index=['11/01','11/02','11/03']
df2 = pd.DataFrame(np.array([[2, 4, 6], [8, 10, 12], [14, 16, 18]]),
                    columns=['Airport1', 'Airport2', 'Airport3'])
df2.index.name='Dates'
df2.index=['11/04','11/05','11/06']
display(df1,df2)

Dates **Airport1** **Airport3** **Airport4** 
11/01   1.            2.          3.  
11/02   4.            5.          6.   
11/03   7.            8.          9.

Dates **Airport1** **Airport2** **Airport3**
11/04   2.           4.           6
11/05   8.           10.          12
11/06   14.          16.          18

我希望 for 循環具有的結果是:

Dates **Airport1** **Airport2** **Airport3** **Airport4**
11/01   1.              NAN.         2.           3
11/02.  4.              NAN.         5.           6
11/03.  7.              NAN.         8.           9
11/04.  2.               4.          6.          NAN      
11/05.  8.              10.          12.         NAN
11/06.  14.             16.          18.         NAN

另一個注意事項是我有 25 個數據幀要合並和計數,所以我希望 for 循環能夠接收無限數據幀。 提前非常感謝!!!

IIUC,您可以嘗試pd.concatdf.sort_index

df = pd.concat([df1, df2]).sort_index(axis=1)

如果有兩個以上的數據框,請使用:

from functools import reduce

dfs = [df1, df2] # list of all dataframes that need's to be combined
df = reduce(lambda d1, d2: pd.concat([d1, d2]), dfs).sort_index(axis=1)

結果:

# print(df)

       Airport1  Airport2  Airport3  Airport4
11/01         1       NaN         2       3.0
11/02         4       NaN         5       6.0
11/03         7       NaN         8       9.0
11/04         2       4.0         6       NaN
11/05         8      10.0        12       NaN
11/06        14      16.0        18       NaN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM