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

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

使用 groupby 構造數據框

使用 groupby 構造數據框

莫回無 2023-05-23 14:43:30
我的數據框如下所示:                date    id     pct_change12355258    2010-07-28  60059   0.21021012355265    2010-07-28  60060   0.59200012355282    2010-07-29  60059   0.30027312355307    2010-07-29  60060   0.48198212355330    2010-07-28  60076   0.400729我想用“目標”、“來源”、“權重”列來編寫它,其中:“目標”和“來源”都是“id”,“權重”計算“目標”和“權重”的天數“來源”同時改變了價格。所以它看起來像:target  source  weights60059   60060   260059   60076   1   60060   60076   1我的目標是使用此數據框制作一個 networkx 圖。我試過使用 groupbydf.groupby(['date','id'])['id'].unique().value_counts()df.groupby(['date','id'])['id'].count()和 for 循環(這很糟糕)。我覺得我在 groupby 中少了一小步,但又說不出少了什么。感謝您的幫助。
查看完整描述

4 回答

?
千萬里不及你

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

pivto_table這個想法是如果 id 對每個日期都有 pct_change,則使用first 來獲得 True


#first pivot to get True if any value of id for a date

df_ = df.pivot_table(index='id', columns='date', values='pct_change', 

                     aggfunc=any, fill_value=False)

print(df_)

date  2010-07-28 2010-07-29

id                         

60059       True       True

60060       True       True

60076       True      False

然后,您可以使用combinationfromitertools創建所有可能的對,使用它們來選擇行,并使用&運算符查看在同一日期兩者都為 True 的位置,沿列求和(獲取權重列)。將此列分配給從兩個組合列表創建的數據框。


# get all combinations of ids

from itertools import combinations

a, b = map(list, zip(*combinations(df_.index, 2)))


res = (pd.DataFrame({'target':a, 'source':b})

         .assign(weigths=(df_.loc[a].to_numpy()

                          &df_.loc[b].to_numpy()

                         ).sum(axis=1))

      )

print(res)

   target  source  weigths

0   60059   60060        2

1   60059   60076        1

2   60060   60076        1

注意:不要忘記用您的分類列的名稱更改index='id'中的pivot_table,否則您的計算機很可能無法處理以下操作并崩潰


查看完整回答
反對 回復 2023-05-23
?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

嘗試這個


import pandas as pd, numpy as np


ids = df.id.unique()

WeightDf = pd.DataFrame(index=ids, columns=ids)

WeightDf.loc[:, :] = 0


def weigh(ID):

    IdDates =  set(df.loc[df.id==ID].date.to_list())

    for i in ids:

        WeightDf.at[ID, i] = len(set.intersection(set(df.loc[df.id==i].date.to_list()), IdDates))

        

pd.Series(ids).apply(weigh)

print(WeightDf)


import itertools as itt

result = pd.DataFrame(columns=['Id1', 'Id2', 'Weight'])

for i1, i2 in itt.combinations(ids, 2):

    result = pd.concat([result, pd.DataFrame(data=[{'Id1':i1, 'Id2':i2,'Weight':WeightDf.loc[i1, i2]}])])


print(result)


查看完整回答
反對 回復 2023-05-23
?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

看到這個用例的很多變化 - 生成組合


import itertools


df = pd.read_csv(io.StringIO("""                date    id     pct_change

12355258    2010-07-28  60059   0.210210

12355265    2010-07-28  60060   0.592000

12355282    2010-07-29  60059   0.300273

12355307    2010-07-29  60060   0.481982

12355330    2010-07-28  60076   0.400729"""), sep="\s+")


# generate combinations of two... edge case when a group has only one member

# tuple of itself to itself

dfx = (df.groupby('date').agg({"id": lambda s: list(itertools.combinations(list(s), 2))

                               if len(list(s))>1 else [tuple(list(s)*2)]})

    .explode("id")

     .groupby("id").agg({"id":"count"})

     .rename(columns={"id":"weights"})

     .reset_index()

     .assign(target=lambda dfa: dfa["id"].apply(lambda s: s[0]),

           source=lambda dfa: dfa["id"].apply(lambda s: s[1]))

     .drop(columns="id")

)


print(dfx.to_string(index=False))

輸出


 weights  target  source

       2   60059   60060

       1   60059   60076

       1   60060   60076


查看完整回答
反對 回復 2023-05-23
?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

groupby + value_counts。

這是代碼,以使將來的人們更容易使用:

from itertools import combinations


def combine(batch):

? ? """Combine all products within one batch into pairs"""

? ? return pd.Series(list(combinations(set(batch), 2)))


edges = df.groupby('date')['id'].apply(combine).value_counts()


c = ['source', 'target']

L = edges.index.values.tolist()

edges = pd.DataFrame(L, columns=c).join(edges.reset_index(drop=True))


查看完整回答
反對 回復 2023-05-23
  • 4 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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