[英]Dropping a Pandas Row based on the prefix of value in a column
我有一個數據框df
其中有一列稱為Account Number
。 我正在嘗試刪除帳戶的前兩個字母為“ AA”或“ BB”的行
import pandas as pd
df = pd.DataFrame(data=["AA121", "AB1212", "BB121"],columns=['Account'])
print df
df = df[df['Account Number'][2:] not in ['AA', 'BB']]
錯誤:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
您可以嘗試contains
:
import pandas as pd
df = pd.DataFrame(data=["AA121", "AB1212", "BB121"],columns=['Account'])
print df
Account
0 AA121
1 AB1212
2 BB121
print df['Account'].str[:2]
0 AA
1 AB
2 BB
Name: Account, dtype: object
print df['Account'].str[:2].str.contains('AA|BB')
0 True
1 False
2 True
Name: Account, dtype: bool
df = df[~(df['Account'].str[:2].str.contains('AA|BB'))]
print df
Account
1 AB1212
或使用startswith
:
print ((df['Account'].str[:2].str.startswith('AA')) |
(df['Account'].str[:2].str.startswith('BB')))
0 True
1 False
2 True
Name: Account, dtype: bool
print ~((df['Account'].str[:2].str.startswith('AA')) |
(df['Account'].str[:2].str.startswith('BB')))
0 False
1 True
2 False
Name: Account, dtype: bool
df = df[~((df['Account'].str[:2].str.startswith('AA')) |
(df['Account'].str[:2].str.startswith('BB')))]
print df
Account
1 AB1212
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.