Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 跨多个列删除连续的重复项-熊猫_Python_Pandas - Fatal编程技术网

Python 跨多个列删除连续的重复项-熊猫

Python 跨多个列删除连续的重复项-熊猫,python,pandas,Python,Pandas,在这方面有一些问题,但不使用基于位置的多列索引: 我有一个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'],

在这方面有一些问题,但不使用基于位置的多列索引:

我有一个
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:必须仅传递带有布尔值的数据帧

TypeError:-:“str”和“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
在这里不合适,因为我只想删除与前一行相同的行。我不想完全删除相同的值

我想删除
销售
中的值相同的行,这意味着您可以计算差异,检查它们在
销售
中是否等于零:

# if the data are numeric
# s = df[['year','sale']].diff().ne(0).any(1)

s = df[['year','sale']].ne(df[['year','sale']].shift()).any(1)
df[s]
输出:

   month  year  sale
0      1  2012    55
1      4  2014    40
3     10  2013    84
4     12  2014    31
5     12  2014    32
我想删除
销售
中的值相同的行,这意味着您可以计算差值,检查它们在
销售
中是否等于零:

# if the data are numeric
# s = df[['year','sale']].diff().ne(0).any(1)

s = df[['year','sale']].ne(df[['year','sale']].shift()).any(1)
df[s]
输出:

   month  year  sale
0      1  2012    55
1      4  2014    40
3     10  2013    84
4     12  2014    31
5     12  2014    32

这够了吗?groupby(['year','sale'],as_index=False)。first()所以,不能是硬编码标签。将更新问题。groupby Tooby的性能可能令人担忧,这就足够了吗?groupby(['year','sale'],as_index=False)。first()所以,不能是硬编码标签。将更新问题。groupby Too可能会担心性能,抱歉它们是字符串@QuangHoang@jonboy请参见使用
shift
更新。但是为什么您希望/让
销售
作为文本。直觉上,它们是数值的。是的,它并不代表我的实际数据。这是一套虚拟装置。如果你把它改成基于索引的,那就太好了
df=df[df.iloc[:,1:3].ne(df.iloc[:,1:3].shift()).any(1)].reset_index(drop=True)
您也可以使用
cols=df.iloc[:,1:3];df[cols.ne(cols.shift()).any(1)]
。抱歉,它们是字符串@QuangHoang@jonboy请参见使用
shift
更新。但是为什么您希望/让
销售
作为文本。直觉上,它们是数值的。是的,它并不代表我的实际数据。这是一套虚拟装置。如果你把它改成基于索引的,那就太好了
df=df[df.iloc[:,1:3].ne(df.iloc[:,1:3].shift()).any(1)].reset_index(drop=True)
您也可以使用
cols=df.iloc[:,1:3];df[cols.ne(cols.shift()).any(1)]