如果我想要删除一行

时间:2018-04-01 13:11:40

标签: python pandas dataframe indexing data-manipulation

我在python代码中有一个名为df1的数据框:

    SYMBOL    TYPE          DATE       VALUE
0    ABC     Normal       29-03-2018     100
1    DEF     Artificial   30-03-2018      96
2    DEF     Normal       01-04-2018     105

和5000个这样的行

我想删除包含TYPE = Artificial的行 我写了下面的代码,但它给出了一个错误

for i in df1:
    if df1['trade_type'] == 'Artificial':
        del df1[i]
print(df1)

它给出错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

2 个答案:

答案 0 :(得分:0)

尝试使用以下内容:

df1 = df1.drop(df1[df1['TYPE'] == 'Artificial'].index)

答案 1 :(得分:0)

import pandas as pd

data = '''\
SYMBOL    TYPE          DATE       VALUE
ABC     Normal       29-03-2018     100
DEF     Artificial   30-03-2018      96
DEF     Normal       01-04-2018     105'''

df = pd.read_csv(pd.compat.StringIO(data), sep='\s+')

# Create a mask
m = df.TYPE != 'Artificial'

# Reassign with mask
df = df.loc[m]