我想用try / except在python中应用过滤器。我该怎么做?我的意思是类似于“尝试过滤de csv,如果您不能这样做,因为'ON'
或'OFF'
不在行df_ok = df
中”
import pandas as pd
df = pd.read_csv('a.csv')
try:
df_ok = df.loc[df['Precio'] != 'ON']
df_ok = df_ok.loc[df_ok['Precio'] != 'OFF']
csv:
Espacio País Precio
0 4083496 * ON
1 4083554 * OFF
2 4083368 * ON
3 4083194 * OFF
4 4083194 * ON
5 4083194 * OFF
6 4083194 * ON
7 4083194 * ON
8 MARTIN * 0.5
9 MARTIN * 89
10 MARTIN * 198
答案 0 :(得分:3)
这是一种方法:
df
Out[110]:
Espacio País Precio
0 4083496 * ON
1 4083554 * OFF
2 4083368 * ON
3 4083194 * OFF
4 4083194 * ON
5 4083194 * OFF
6 4083194 * ON
7 4083194 * ON
8 MARTIN * 0.5
9 MARTIN * 89
10 MARTIN * 198
df[~df['Precio'].str.contains('ON|OFF')]
Out[111]:
Espacio País Precio
8 MARTIN * 0.5
9 MARTIN * 89
10 MARTIN * 198
答案 1 :(得分:1)
我认为您可能更适合以下条件:
import pandas as pd
df = pd.read_csv('a.csv')
filtered_df = df[df['Precio']=='ON' | df['Precio']=='OFF']
# Then check if filtered_df is empty
答案 2 :(得分:0)
您想要做的是将Precio不是“ ON”和“ OFF”之一的所有行都分隔出来
df[~df['Precio'].isin(['ON','OFF'])]
Out[111]:
Espacio País Precio
8 MARTIN * 0.5
9 MARTIN * 89
10 MARTIN * 198