run*_*man 15 python numpy pandas
我想选择值不以某些str开头的行.例如,我有一只熊猫df,我想选择不开始的数据t,和c.在此示例中,输出应为mext1和okl1.
import pandas as pd
df=pd.DataFrame({'col':['text1','mext1','cext1','okl1']})
df
col
0 text1
1 mext1
2 cext1
3 okl1
Run Code Online (Sandbox Code Playgroud)
我要这个:
col
0 mext1
1 okl1
Run Code Online (Sandbox Code Playgroud)
Ted*_*rou 25
您可以使用str访问器来获取字符串功能.该get方法可以获取字符串的给定索引.
df[~df.col.str.get(0).isin(['t', 'c'])]
col
1 mext1
3 okl1
Run Code Online (Sandbox Code Playgroud)
看起来您也可以使用startswith要排除的值的元组(而不是列表).
df[~df.col.str.startswith(('t', 'c'))]
Run Code Online (Sandbox Code Playgroud)
piR*_*red 16
选项1
使用str.match和负向前看
df[df.col.str.match('^(?![tc])')]
Run Code Online (Sandbox Code Playgroud)
选项2
内query
df.query('col.str[0] not list("tc")')
Run Code Online (Sandbox Code Playgroud)
选项3
numpy广播
df[(df.col.str[0][:, None] == ['t', 'c']).any(1)]
Run Code Online (Sandbox Code Playgroud)
col
1 mext1
3 okl1
Run Code Online (Sandbox Code Playgroud)
时间测试
def ted(df):
return df[~df.col.str.get(0).isin(['t', 'c'])]
def adele(df):
return df[~df['col'].str.startswith(('t','c'))]
def yohanes(df):
return df[df.col.str.contains('^[^tc]')]
def pir1(df):
return df[df.col.str.match('^(?![tc])')]
def pir2(df):
return df.query('col.str[0] not in list("tc")')
def pir3(df):
df[(df.col.str[0][:, None] == ['t', 'c']).any(1)]
functions = pd.Index(['ted', 'adele', 'yohanes', 'pir1', 'pir2', 'pir3'], name='Method')
lengths = pd.Index([10, 100, 1000, 5000, 10000], name='Length')
results = pd.DataFrame(index=lengths, columns=functions)
from string import ascii_lowercase
for i in lengths:
a = np.random.choice(list(ascii_lowercase), i)
df = pd.DataFrame(dict(col=a))
for j in functions:
results.set_value(
i, j,
timeit(
'{}(df)'.format(j),
'from __main__ import df, {}'.format(j),
number=1000
)
)
fig, axes = plt.subplots(3, 1, figsize=(8, 12))
results.plot(ax=axes[0], title='All Methods')
results.drop('pir2', 1).plot(ax=axes[1], title='Drop `pir2`')
results[['ted', 'adele', 'pir3']].plot(ax=axes[2], title='Just the fast ones')
fig.tight_layout()
Run Code Online (Sandbox Code Playgroud)
你可以使用str.startswith和否定它.
df[~df['col'].str.startswith('t') &
~df['col'].str.startswith('c')]
col
1 mext1
3 okl1
Run Code Online (Sandbox Code Playgroud)
或者更好的选择,根据@Ted Petrou在元组中有多个字符:
df[~df['col'].str.startswith(('t','c'))]
col
1 mext1
3 okl1
Run Code Online (Sandbox Code Playgroud)