[英]How can I add a column to a dataframe with a value conditional on another dataframe?
[英]How can i add a column to a dataframe based on a conditional of another dataframe that has a different length, but shared column data
我有兩個不同長度和不同列的數據框,但有一個具有相同標識數據的共享列。 他們看起來像這樣
觀察DF:
指數 | 科學名稱 | 公園名稱 | 觀察 |
---|---|---|---|
0 | 姓名1 | 公園1 | 10 |
1個 | 名字2 | 公園2 | 12 |
物種自由度:
指數 | 科學名稱 | 通用名稱 | 類別 |
---|---|---|---|
0 | 姓名1 | 名稱 1,名稱 2 | 哺乳動物 |
1個 | 名字2 | 名稱 1,名稱 2 | 維管植物 |
我正在嘗試在 observatiosn DF 中創建一個名為“category”的新列,該列基於兩個表之間共享的 scientific_names 填充數據。 我試過使用 pd.merge 但它沒有按照我想要的方式填充類別列。 Concat 也沒有。 當我嘗試使用列表理解時,它也給了我一個值錯誤。 有什么想法嗎?
我試過像這樣使用列表理解:
observations['category'] = [el for el in species['category'] if observations['scientific_name'] == species['scientific_name]]
這會導致錯誤。
如果您只想將species
的“類別”列添加到基於共享列“scientific_name”的observations
,這應該可行。
observations = pd.merge(observations, species[['scientific_name', 'category']])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.