我有一個包含三列的 Pandas 資料框:句子、關鍵短語、類別。關鍵短語列包含一個空串列或它來自的句子行中的單詞/短語,如下所示:
| 句子 | 關鍵短語 | 類別 |
|---|---|---|
| 紅球 | ['red ball'] |
目的 |
| 一個藍色的大盒子 | ['blue'] |
目的 |
| 他扔紅球 | ['he throws','red ball'] |
行動 |
我想檢查整個關鍵短語列的內容,并為每個獨特的短語建立一個頻率詞典(或最好的)。所以在我的例子中,我會有類似的東西:'red ball': 2, 'blue': 1, 'he throws': 1
然后我想計算這些關鍵短語在資料框中所有類別的頻率分布。所以在我的例子中,物件類別是 100% 的'blue'出現,但只有 50% 的'red ball'。我假設最好的方法是從我上面提到的頻率字典開始?
最后,我想在資料框中添加另一列,該列將針對其行中的每個關鍵短語顯示該類別中該關鍵短語出現的百分比。
所以最終的 DF 看起來像這樣,盡管只要資訊存在,審美并不重要:
| 句子 | 關鍵短語 | 類別 | 關鍵短語出現 |
|---|---|---|---|
| 紅球 | ['red ball'] |
目的 | 紅球:50% |
| 一個藍色的大盒子 | ['blue'] |
目的 | 藍色:100% |
| 他扔紅球 | ['he throws', 'red ball'] |
行動 | 他投擲:100%,紅球:50% |
擁有像字典這樣的東西也很有用,其中每個鍵都是類別,每個值都包含該類別中出現的所有關鍵短語及其流行程度,所以也許這會在我創建的初始字典中?
uj5u.com熱心網友回復:
你可以試試
df['Key Phrase Ocurrences'] = 100 * df.nunique(axis = 1)/df.count(axis = 1)
uj5u.com熱心網友回復:
首先我們分解 df 所以我們有一行一行的關鍵短語:
df2 = df.explode('Key Phrases')
df2
輸出:
Sentence Key Phrases Category
0 the red ball red ball object
1 a big blue box blue object
2 he throws the red ball he throws action
2 he throws the red ball red ball action
然后我們創建一個出現的表,如下所示:
df3 = df2.groupby(['Key Phrases','Category'])['Sentence'].count().unstack().fillna(0)
df3
輸出:
Category action object
Key Phrases
blue 0.0 1.0
he throws 1.0 0.0
red ball 1.0 1.0
然后我們通過將出現次數除以總數來轉換為頻率
df4 = df3.apply(lambda c: c/df3.sum(axis=1))
df4
輸出:
Category action object
Key Phrases
blue 0.0 1.0
he throws 1.0 0.0
red ball 0.5 0.5
這回答了您問題的第 1 部分
要將其擬合回原始資料,我們可以執行以下操作。對已經爆炸的版本資料框更容易做到這一點df2:
df2.merge(df4.unstack().rename('freq').reset_index(), how = 'left', on = ['Category', 'Key Phrases'])
輸出:
Sentence Key Phrases Category freq
-- ---------------------- ------------- ---------- ------
0 the red ball red ball object 0.5
1 a big blue box blue object 1
2 he throws the red ball he throws action 1
3 he throws the red ball red ball action 0.5
這包含您想查看的所有資訊,盡管不可否認的格式不是很漂亮。正如你所說的格式并不重要,我會把它留在這里,但你總是可以做進一步groupby的等等
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/415699.html
標籤:
下一篇:Django與熊貓
