簡體   English   中英

如何根據熊貓中的依賴值更新數據框?

[英]How to update dataframe based on dependent value in pandas?

我必須根據依賴值更新數據幀。 如何才能做到這一點?

例如,輸入數據幀df

id      dependency
10
20       30
30       40
40
50       10
60       20     

這里我們有: 20 -> 3030 -> 40 所以最終結果將是20 -> 4030 -> 40

以同樣的方式, 60 -> 20 -> 30 -> 40所以最終結果將是60 -> 40

最后結果:

id      dependency   final_dependency
10
20       30            40
30       40            40
40
50       10            10
60       20            40

您可以使用networkx來執行此操作。 首先,創建一個具有依賴關系的節點的圖:

df_edges = df.dropna(subset=['dependency'])
G = nx.from_pandas_edgelist(df_edges, create_using=nx.DiGraph, source='dependency', target='id')

現在,我們可以找到每個節點的根祖先並將其添加為一個新列:

def find_root(G, node):
    ancestors = list(nx.ancestors(G, node))
    if len(ancestors) > 0:
        root = find_root(G, ancestors[0])
    else:
        root = node
    return root

df['final_dependency'] = df['id'].apply(lambda x: find_root(G, x))
df['final_dependency'] = np.where(df['final_dependency'] == df['id'], np.nan, df['final_dependency'])

結果數據框:

   id  dependency  final_dependency
0  10         NaN               NaN
1  20        30.0              40.0
2  30        40.0              40.0
3  40         NaN               NaN
4  50        10.0              10.0
5  60        20.0              40.0

一種方法是創建自定義函數:

s = df[df["dependency"].notnull()].set_index("id")["dependency"].to_dict()

def func(val):
    if not s.get(val):
        return None
    while s.get(val):
        val = s.get(val)
    return val

df["final"] = df["id"].apply(func)

print (df)

   id  dependency  final
0  10         NaN    NaN
1  20        30.0   40.0
2  30        40.0   40.0
3  40         NaN    NaN
4  50        10.0   10.0
5  60        20.0   40.0

你已經有了一些答案。 iterrows() 是一個有點昂貴的解決方案,但希望你也有這個。

import pandas as pd

raw_data = {'id': [i for i in range (10,61,10)],
            'dep':[None,30,40,None,10,20]}
df = pd.DataFrame(raw_data)

df['final_dep'] = df.dep

for i,r in df.iterrows():

    if pd.notnull(r.dep):
        x = df.loc[df['id'] == r.dep, 'dep'].values[0]
        if pd.notnull(x):
            df.iloc[i,df.columns.get_loc('final_dep')] = x
        else:
            df.iloc[i,df.columns.get_loc('final_dep')] = r.dep

print (df)

輸出將是:

   id   dep final_dep
0  10   NaN       NaN
1  20  30.0        40
2  30  40.0        40
3  40   NaN       NaN
4  50  10.0        10
5  60  20.0        30

暫無
暫無

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

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