0
我有一個包含ID和電子郵件的數據框。我也有一本字典,它包含一個關鍵的id和一個電話號碼。我想在字典上找到它,如果字典中存在該id,則在數據框中創建一個新列並添加電話號碼。我想通了,怎麼看如果ID存在於詞典中,而不是去創造一個新的列:向數據框中的某一行添加一列pandas
for wid in mapping_id_phone:
print any(id==wid)
我有一個包含ID和電子郵件的數據框。我也有一本字典,它包含一個關鍵的id和一個電話號碼。我想在字典上找到它,如果字典中存在該id,則在數據框中創建一個新列並添加電話號碼。我想通了,怎麼看如果ID存在於詞典中,而不是去創造一個新的列:向數據框中的某一行添加一列pandas
for wid in mapping_id_phone:
print any(id==wid)
您可以使用map
:
df['new'] = df.id.map(mapping_id_phone)
樣品:
df = pd.DataFrame({'id':[1,2,3]})
mapping_id_phone = {1: '123', 2:'456', 3:'789'}
print (df)
id
0 1
1 2
2 3
df['new'] = df.id.map(mapping_id_phone)
print (df)
id new
0 1 123
1 2 456
2 3 789
如果dict
中的某些值丟失,您將獲得NaN
:
df = pd.DataFrame({'id':[1,2,3, 4]})
mapping_id_phone = {1: '123', 2:'456', 3:'789'}
print (df)
id
0 1
1 2
2 3
3 4
df['new'] = df.id.map(mapping_id_phone)
print (df)
id new
0 1 123
1 2 456
2 3 789
3 4 NaN
對不起'df ['new_col'] = df ['my_warner_id'] .map(mapping_id_phone)'? – EdChum