列に他の列の値が含まれているかどうかを確認し、3番目の列にTrueまたはFalseを入力したいと思います。
df in:
id | name | account
-------------------
01 | John | AB01
02 | Emma | AB03
03 | Alice | AB03
df out:
id | name | account | match
----------------------------
01 | John | AB01 | True
02 | Emma | AB03 | False
03 | Alice | AB03 | True
私はこれを試しました:
df['match'] = np.where(df['account'].contains(df['id']), 'True','False')
エラー:AttributeError: 'Series'オブジェクトに属性がありません 'contains'
df['match'] = np.where(df['account'].str.contains(df['id']), 'True','False')
エラー:TypeError: 'Series'オブジェクトは変更可能であるため、ハッシュできません
どんな助けでも大歓迎です!
行ごとの値が含まれているかどうかをテストするにはapply
、in
ブール値の場合True, False
:
df['match'] = df.apply(lambda x: x['id'] in x['account'], axis=1)
文字列の場合'True', 'False'
:
df['match'] = np.where(df.apply(lambda x: x['id'] in x['account'], axis=1), 'True','False')
print (df)
id name account match
0 01 John AB01 True
1 02 Emma AB03 False
2 03 Alice AB03 True
編集:
欠落している値があるため、考えられる解決策はを使用することnp.nan == np.nan
ですFalse
。したがって、次のif-else
ステートメントを追加します。
print (df)
id name account
0 01 John AB01
1 02 Emma NaN
2 03 Alice AB03
ブール値の場合True, False
:
df['match'] = df.apply(lambda x: x['id'] in x['account']
if x['account'] == x['account']
else False, axis=1)
文字列の場合'True', 'False'
:
df['match'] = np.where(df.apply(lambda x: x['id'] in x['account']
if x['account'] == x['account']
else False, axis=1), 'True','False')
print (df)
id name account match
0 01 John AB01 True
1 02 Emma NaN False
2 03 Alice AB03 True
別のアイデアは、try-exception
ステートメントでカスタム関数を使用することです。
def test(x):
try:
return x['id'] in x['account']
except Exception:
return False
ブール値の場合True, False
:
df['match'] = df.apply(test, axis=1)
文字列の場合'True', 'False'
:
df['match'] = np.where(df.apply(test, axis=1), 'True','False')
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加