熊猫| 根据条件复制数据框值

用户名

我有一个DataFrame,,X格式如下:

Value1   Value2   Value3   Month   Area

   1       1        3        0      1
   4       10       45       1      1
   ..      ..       ..       ..     .. 
   15      11       10       34     1
   10      21       12       35     1
   1       2        2        0      2
   3       4        4        1      2
   ..      ..       ..       ..     .. 
   27      39       21       34     2
   23      42       32       35     2
   ..      ..       ..       ..     .. 

DataFrame X,我想创建一个和DataFrame Y,除了Month以外的其他列Area的行Y必须相对于Area列,但具有的行的列值X+1

例如,如果面积为1,则的第一行将Y包含的第二行的值X

Value1   Value2   Value3   (Index) (Area)   

   4       10       45        0     1
   ..      ..       ..       ..     .. 
   10      21       12       34     1
   3       4        4        35     2
   ..      ..       ..       ..     .. 
   23      42       32       69     2
   ..      ..       ..       ..     ..

然后,我需要为每个删除X其中包含最后一个Month的行Area

然后DataFrame X将其转换为以下内容:

Value1   Value2   Value3   Month   Area

   1       1        3        0      1
   4       10       45       1      1
   ..      ..       ..       ..     .. 
   15      11       10       34     1
   1       2        2        0      2
   3       4        4        1      2
   ..      ..       ..       ..     .. 
   27      39       21       34     2
   ..      ..       ..       ..     .. 

这是我目前的代码:

#Define a list of indexes of X to Drop
to_drop = list()
prev = None
y_index = 0
    
    
    #Iterate through X
    for index, row in x.iterrows():
        if not prev is None:
            
            #If the Area is the same as before
            if row['Area'] == prev :
                #Append to the Y dataframe and increase y's index
                y.loc[y_index] = row[y_columns]
                y_index+=1
            #We found a new index. We want to delete the previous one, which will have the last 
            #month value for the previous area
            else: to_drop.append(prev_index)
            
        prev_index= index
        prev = row['Area']
    
    print("Removing some rows...")
    x = x.drop(x.index[to_drop])

但是,当我检查新的时DataFrames,它们似乎丢失了很多信息,例如全部Areas被清除掉了。有更好的方法的想法,我可能做错了什么?

请注意,这是一个示例。数据集由几千个Area值组成,周围有多个30 Month值。

提前致谢。

斯科特·波士顿

尝试这个:

df['Month'] = df['Month'].shift()
df = df.dropna(subset=['Month'], axis=0)
df[df.duplicated('Area', keep='last')]

较旧的解决方案

drop_duplicates对你有用吗?

df.drop_duplicates(['Area'], keep='first')

输出:

   Value1  Value2  Value3  Month  Area
0       1       1       3      0     1
2       1       2       2      0     2

和,

df.drop_duplicates(['Area'], keep='last')

输出:

   Value1  Value2  Value3  Month  Area
1       4      10      45      1     1
3       3       4       4      1     2

更新,删除每个组中的最后一条记录:

df[df.duplicated('Area', keep='last')]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章