[英]Pandas DataFrame - Creating a new column from a comparison
我正在嘗試使用“代碼”列中的值創建一個名為“ city_code”的列。 但是為了做到這一點,我需要比較“ ds_city”和“ city”的值是否相等。
這是一個表示例:
https://i.imgur.com/093GJF1.png
我已經試過了:
def find_code(data):
if data['ds_city'] == data['city'] :
return data['code']
else:
return 'UNKNOWN'
df['code_city'] = df.apply(find_code, axis=1)
但是,由於在“ ds_city”列中存在重復項,因此結果是:
https://i.imgur.com/geHyVUA.png
這是預期結果的圖像:
https://i.imgur.com/HqxMJ5z.png
我該如何解決?
您可以使用熊貓合並:
df = pd.merge(df, df[['code', 'city']], how='left',
left_on='ds_city', right_on='city',
suffixes=('', '_right')).drop(columns='city_right')
# output:
# code city ds_city code_right
# 0 1500107 ABAETETUBA ABAETETUBA 1500107
# 1 2900207 ABARE ABAETETUBA 1500107
# 2 2100055 ACAILANDIA ABAETETUBA 1500107
# 3 2300309 ACOPIARA ABAETETUBA 1500107
# 4 5200134 ACREUNA ABARE 2900207
這是pandas.merge的文檔 。 它使用輸入數據幀,並在ds_city
等於city
時將其自身的code
和city
列連接起來。
上面的代碼將填補code_right
當city
沒有與發現nan
。 您可以進一步執行以下操作以將其填充為“未知”:
df['code_right'] = df['code_right'].fillna('UNKNOWN')
這更像是np.where
import numpy as np
df['code_city'] = np.where(data['ds_city'] == data['city'],data['code'],'UNKNOWN')
您可以嘗試一下:
# Begin with a column of only 'UNKNOWN' values.
data['code_city'] = "UNKNOWN"
# Iterate through the cities in the ds_city column.
for i, lookup_city in enumerate(data['ds_city']):
# Note the row which contains the corresponding city name in the city column.
row = data['city'].tolist().index(lookup_city)
# Reassign the current row's code_city column to that code from the row we found in the last step.
data['code_city'][i] = data['code'][row]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.