[英]python dataframe create one column based on another column
我想在 dataframe 中創建另一個列。
dataframe如下,sub_id是id的一部分,說id是sub_id的'parent',它包括id本身和id中包含的一些項目。
id 沒有名字,但 sub_id 有對應的名字
我想用 sub_id 的名字檢查 id,然后創建 id 的名字
df = pd.DataFrame({'id':[1,1,1,2,2],
'sub_id':[12,1,13,23,2],
'name':['pear','fruit','orange','cat','animal']})
id sub_id name
0 1 12 pear
1 1 1 fruit
2 1 13 orange
3 2 23 cat
4 2 2 animal
我想創建另一個列 id_name,以獲得:
id sub_id name id_name
0 1 12 pear fruit
1 1 1 fruit fruit
2 1 13 orange fruit
3 2 23 cat animal
4 2 2 animal animal
我不知道如何有效地實現它,我只想合並 dataframe 兩次,但我認為有更好的方法。
如果將不匹配的id
與 sub_id 替換為在sub_id
中的Series.where
值,則GroupBy.transform
將first
工作,因為返回第一個非缺失值:
df['id_name'] = (df['name'].where(df['id'].eq(df['sub_id']))
.groupby(df['id'])
.transform('first'))
或者通過Series.map
掩碼和映射助手 Series 過濾行:
s = df[df['id'].eq(df['sub_id'])].set_index('id')['name']
df['id_name'] = df['id'].map(s)
print (df)
id sub_id name id_name
0 1 12 pear fruit
1 1 1 fruit fruit
2 1 13 orange fruit
3 2 23 cat animal
4 2 2 animal animal
詳情:
print (df['name'].where(df['id'].eq(df['sub_id'])))
0 NaN
1 fruit
2 NaN
3 NaN
4 animal
Name: name, dtype: object
print (s)
id
1 fruit
2 animal
Name: name, dtype: object
你的ID是獨一無二的嗎?
您使用GroupBy.transform
獲取每個組的min
id 並將map
用於現有id
:
df['id_name'] = (df.groupby('id')['sub_id'].transform('min')
.map(df.set_index('sub_id')['name'])
)
output:
id sub_id name id_name
0 1 12 pear fruit
1 1 1 fruit fruit
2 1 13 orange fruit
3 2 23 cat animal
4 2 2 animal animal
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.