我創建了以下空資料框:
columns = ['Band','Tree','Foot']
rows = ['Hand', 'Foot', 'Shoulder']
df = pd.DataFrame(index=rows, columns=columns)
我想計算列和行之間的距離,目前正在使用以下代碼:
import pandas as pd
import nltk
def distance(x):
i = x.index
j = x.name
return nltk.edit_distance(i,j)
df = df.apply(distance)
但這會回傳:
| - | - |
|---|---|
| 樂隊 | 4 |
| 樹 | 4 |
| 腳 | 4 |
我希望它回傳每個單元格對應的列和行之間的距離。
| 樂隊 | 樹 | 腳 | |
|---|---|---|---|
| 手 | 1 | 4 | 4 |
| 腳 | 4 | 4 | 0 |
| 肩膀 | 7 | 7 | 7 |
我錯過了什么?
uj5u.com熱心網友回復:
edit_distance需要 2 個字串,因此您必須遍歷索引。一種選擇是應用在 上執行此操作的 lambda df:
df.apply(lambda col: [nltk.edit_distance(col.name, i) for i in col.index])
但是,我認為首先創建一個包含值的字典而不是填充 DataFrame 更簡單;然后構建一個DataFrame,如下所示:
df = pd.DataFrame({j: {i: nltk.edit_distance(i,j) for i in rows} for j in columns})
輸出:
Band Tree Foot
Hand 1 4 4
Foot 4 4 0
Shoulder 7 7 7
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/439392.html
上一篇:如何洗掉超過一定列數的行
