謝謝你的協助。我無法在資料框中創建新列。
到目前為止,我已經嘗試過使用 lambdas、isin 方法、包含方法。
我有一個包含這些值的資料框(前兩列是 dtype = object,列 c 是我想要得到的):
Country code| Countries || Column c |
KR | KR~CN_SG~PH || Valid |
RO | CN~PK || Invalid |
NL | CZ_BE~NL_IT~DE || Valid |
SG | HK~SK_DZ_AL_CN_GR_RU~SA~SG || Valid |
US | ZA~SE~ES~CH_UA || Invalid |
有效 - 當國家代碼在國家/地區時
無效 - 如果不是
這是我第一次在 Python 作業中撰寫代碼,如果這是個愚蠢的問題,對不起:D
uj5u.com熱心網友回復:
使用串列推導numpy.where:
m = [x in y for x, y in zip(df['Country code'], df['Countries'])]
df['Column c'] = np.where(m, 'Valid','Invalid')
uj5u.com熱心網友回復:
您可以使用單個串列推導:
df['Column c'] = ['Valid' if x in l else 'Invalid'
for x, l in zip(df['Country code'], df['Countries'])]
輸出:
Country code Countries Column c
0 KR KR~CN_SG~PH Valid
1 RO CN~PK Invalid
2 NL CZ_BE~NL_IT~DE Valid
3 SG HK~SK_DZ_AL_CN_GR_RU~SA~SG Valid
4 US ZA~SE~ES~CH_UA Invalid
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/526352.html
上一篇:MVC表單資料無法系結到模型
