簡體   English   中英

基於過濾器添加新列並添加來自另一個 DataFrame 的值

[英]Add new columns and add values from another DataFrame based on a filter

基於過濾器添加新列並添加來自另一個 DataFrame 的值:

我有兩個 DataFrames 如下:infra_df:-

    Name   time  
    net    8am
    stat   8am
    net    8am
    net    8am
    sig    8am
    net    8am

措施_df:-

    tcp_time.  tcp_wait   
    12         33
    22         11
    23         32
    34         11

    

現在我想在 Name 為 net 和 NAN 的其他地方添加從 measure_df 到 infra_df 的列:-

結果_df:-

    Name   time   tcp_time   tcp_wait
    net    8am    12         33
    stat   8am    NAN        NAN
    net    8am    22         11
    net    8am    23         32
    sig    8am    NAN        NAN
    net    8am    34         11

如果 measure_df 的長度與infra_df中的net數量相同,請使用:

m = infra_df['Name'].eq('net')
df = pd.concat([infra_df, measures_df.set_index(m.index[m])], axis=1)
print (df)
   Name time  tcp_time.  tcp_wait
0   net  8am       12.0      33.0
1  stat  8am        NaN       NaN
2   net  8am       22.0      11.0
3   net  8am       23.0      32.0
4   sig  8am        NaN       NaN
5   net  8am       34.0      11.0

以 net 為 Name 的示例索引:

idx = intra_df.loc[intra_df["Name"].eq("net")].index

我們將measures_df與修改后的索引連接起來:

intra_df = pd.concat([intra_df, measures_df.iloc[:len(idx),:].set_index(idx)], axis=1)

我還添加了 iloc,以防 measure_df 中的行數多於 intra_df 中的 net 行數。

.dropna() 如果這是您需要的,則刪除所有 nan 行。

暫無
暫無

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

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