在这方面有一些问题,但不使用基于位置的多列索引:Pandas: Drop consecutive duplicates
我有一个df
,它可能包含跨特定行的连续重复值。我只想删除最后两列的内容。使用下面的df
,我想删除year
和sale
中的值相同的行
我使用下面的查询得到一个错误
import pandas as pd
df = pd.DataFrame({'month': [1, 4, 7, 10, 12, 12],
'year': ['12', '14', '14', '13', '15', '15'],
'sale': ['55', '40', '40', '84', '31', '32']})
cols = df.iloc[:,1:3]
# Option 1
df = df.loc[df[cols] != df['cols'].shift()].reset_index(drop = True)
ValueError: Must pass DataFrame with boolean values only
# Option 2
df = df[df.iloc[:,1:3].diff().ne(0).any(1)].reset_index(drop = True)
TypeError: unsupported operand type(s) for -: 'str' and 'str'
预期产出:
month year sale
0 1 2012 55
1 4 2014 40
3 10 2013 84
4 12 2014 31
5 12 2014 32
注:
1)我需要使用索引标签来选择列,因为标签将更改。我需要一些液体
2)drop_duplicates
在这里不合适,因为我只想删除与前一行相同的行。我不想完全删除相同的值
我想删除
year
和sale
中的值相同的行,这意味着您可以计算差值,检查它们在year
和sale
上是否等于零:输出:
相关问题 更多 >
编程相关推荐