我有一個熊貓資料框:列標題稱為“位置”示例內容:“倫敦阿恩代爾中心”“曼徹斯特阿恩代爾”“伯明翰中央車站”“紐卡斯爾地鐵中心”
2個numpy陣列:
originalLocation = np.array(["London Arndale Centre","Manchester Arndale","Birmingham Central Station","Newcastle Metro Centre")
newLocation = np.array(["London","Manchester","Birmingham","Newcastle"]
我想在熊貓中創建一個新列:newLocation
結果需要是newLocation中的匹配列,其中位置欄位與原始位置numpy匹配。
例如:“London Arndale Centre”需要是“London” “Manchester Arndale”需要是“Manchester”
我試過這個,但它會拋出錯誤
df['newLocation'] = newLocation[int(np.where(originalLocation == df['Location'])[0])]
錯誤:ValueError:('長度必須匹配才能比較',(159,),(12,))
我在這里做錯了什么?
uj5u.com熱心網友回復:
好像您忘記了originalLocation陣列中的逗號。另外,int()也沒有必要。更新代碼:
df_data = ["London Arndale Centre", "Manchester Arndale", "Birmingham Central Station", "Newcastle Metro Centre"]
df = pd.DataFrame(df_data, columns=['Location'])
originalLocation = np.array(["London Arndale Centre", "Manchester Arndale", "Birmingham Central Station", "Newcastle Metro Centre"])
newLocation = np.array(["London","Manchester","Birmingham","Newcastle"])
df['newLocation'] = newLocation[np.where(originalLocation == df['Location'])[0]]
df
輸出:
Location newLocation
0 London Arndale Centre London
1 Manchester Arndale Manchester
2 Birmingham Central Station Birmingham
3 Newcastle Metro Centre Newcastle
編輯:正如您所提到merge的,即使并非所有值都包含在新位置中,也可以使用。我使用以下方法創建了一個小示例merge:
df_data = ["London Arndale Centre", "Manchester Arndale", "Birmingham Central Station", "Newcastle Metro Centre"]
df = pd.DataFrame(df_data, columns=['Location'])
originalLocation = ["London Arndale Centre", "Birmingham Central Station", "Newcastle Metro Centre"]
newLocation = ["London", "Birmingham", "Newcastle"]
df_new = pd.DataFrame({'Location': originalLocation,
'newLocation': newLocation})
df.merge(df_new, on='Location', how='left')
缺少曼徹斯特條目的輸出:
Location newLocation
0 London Arndale Centre London
1 Manchester Arndale NaN
2 Birmingham Central Station Birmingham
3 Newcastle Metro Centre
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/414374.html
標籤:
上一篇:如何計算陣列每行中點之間的距離
