我們有資料,如下所示:
import pandas as pd
import numpy as np
d = {'shift_city_id': [1, 1,2,3,3,3,1], 'closest_city_id': [np.nan, np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]}
df = pd.DataFrame(data=d)
df
shift_city_id closest_city_id
0 1 NaN
1 1 NaN
2 2 NaN
3 3 NaN
4 3 NaN
5 3 NaN
6 1 NaN
目標是在具有特定 city_id 的單元格中逐一輸入特定值。所以我試試這個:
df.loc[lambda x: (x['shift_city_id']==3),'closest_city_id'].iloc[0]=3
df.loc[lambda x: (x['shift_city_id']==3),'closest_city_id'].iloc[1]=4
df.loc[lambda x: (x['shift_city_id']==3),'closest_city_id'].iloc[2]=5
并且在資料框中沒有任何變化,np.nan 仍然存在。結果應該是:
shift_city_id closest_city_id
0 1 NaN
1 1 NaN
2 2 NaN
3 3 3
4 3 4
5 3 5
6 1 NaN
什么可以解決問題?
uj5u.com熱心網友回復:
你可以這樣做:
df.loc[lambda x: (x['shift_city_id']==3),'closest_city_id'] = [3,4,5]
這給出了想要的輸出:

為了理解分配的不同行為,我遵循這些詳細的答案
uj5u.com熱心網友回復:
動態,以便您一次可以設定多個 id/值:
ids = [3]
id_values = {3: [3, 4, 5]}
df['closest_city_id'] = df[df['shift_city_id'].isin(ids)]['shift_city_id'].replace(id_values)
輸出:
shift_city_id closest_city_id
0 1 NaN
1 1 NaN
2 2 NaN
3 3 3.0
4 3 4.0
5 3 5.0
6 1 NaN
uj5u.com熱心網友回復:
這里 lambda 不是必需的,您可以比較列df['shift_city_id'],并且因為匹配的 3 行可以分配具有長度的串列3:
df.loc[df['shift_city_id']==3,'closest_city_id'] = [3,4,5]
print (df)
shift_city_id closest_city_id
0 1 NaN
1 1 NaN
2 2 NaN
3 3 3.0
4 3 4.0
5 3 5.0
6 1 NaN
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/466662.html
上一篇:根據熊貓中的現有列創建新列
