Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.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:将DataFrame组的最后一个值分配给该组的所有条目_Python_Pandas_Dataframe_Group By_Pandas Groupby - Fatal编程技术网

Python:将DataFrame组的最后一个值分配给该组的所有条目

Python:将DataFrame组的最后一个值分配给该组的所有条目,python,pandas,dataframe,group-by,pandas-groupby,Python,Pandas,Dataframe,Group By,Pandas Groupby,在Python中,我有一个数据帧。我按一列对这个数据帧进行分组,并希望将一列的最后一个值分配给另一列的所有行 我知道我可以通过以下命令选择组的最后一行: import pandas as pd df = pd.DataFrame({'a': (1,1,2,3,3), 'b':(20,21,30,40,41)}) print(df) print("-") result = df.groupby('a').nth(-1) print(result) 结果: a b 0 1 20 1

在Python中,我有一个数据帧。我按一列对这个数据帧进行分组,并希望将一列的最后一个值分配给另一列的所有行

我知道我可以通过以下命令选择组的最后一行:

import pandas as pd

df = pd.DataFrame({'a': (1,1,2,3,3), 'b':(20,21,30,40,41)})
print(df)
print("-")
result = df.groupby('a').nth(-1)
print(result)
结果:

   a   b
0  1  20
1  1  21
2  2  30
3  3  40
4  3  41
-
    b
a    
1  21
2  30
3  41
如何才能将此操作的结果分配回原始数据帧,以便得到如下结果:

   a   b b_new
0  1  20 21
1  1  21 21
2  2  30 30
3  3  40 41
4  3  41 41
用于:

备选方案:

df['b_new'] = df.groupby('a')['b'].transform(lambda x: x.iat[-1])

print(df)
   a   b  b_new
0  1  20     21
1  1  21     21
2  2  30     30
3  3  40     41
4  3  41     41
具有和的解决方案:

计时

N = 10000

df = pd.DataFrame({'a':np.random.randint(1000,size=N),
                   'b':np.random.randint(10000,size=N)})

#print (df)


def f(df):
    return df.join(df.groupby('a')['b'].nth(-1).rename('b_new'), 'a')

#cᴏʟᴅsᴘᴇᴇᴅ1
In [211]: %timeit df['b_new'] = df.a.map(df.groupby('a').b.nth(-1))
100 loops, best of 3: 3.57 ms per loop

#cᴏʟᴅsᴘᴇᴇᴅ2
In [212]: %timeit df['b_new'] = df.a.replace(df.groupby('a').b.nth(-1))
10 loops, best of 3: 71.3 ms per loop

#jezrael1
In [213]: %timeit df['b_new'] = df.groupby('a')['b'].transform('last')
1000 loops, best of 3: 1.82 ms per loop

#jezrael2
In [214]: %timeit df['b_new'] = df.groupby('a')['b'].transform(lambda x: x.iat[-1])
10 loops, best of 3: 178 ms per loop
    
#jezrael3
In [219]: %timeit f(df)
100 loops, best of 3: 3.63 ms per loop
警告


考虑到组的数量,结果不能解决性能问题,这将对其中一些解决方案的计时产生很大影响。

两种可能性,即
groupby
+
nth
+
map
replace

df['b_new'] = df.a.map(df.groupby('a').b.nth(-1))
或者

您还可以将
nth(-1)
替换为
last()
(事实上,这样做恰好会使速度加快一点),但是
nth
可以让您更灵活地从
b
中的每组中选择什么项目



我想这应该很快

df.merge(df.drop_duplicates('a',keep='last'),on='a',how='left')
Out[797]: 
   a  b_x  b_y
0  1   20   21
1  1   21   21
2  2   30   30
3  3   40   41
4  3   41   41
df['b_new'] = df.a.map(df.groupby('a').b.nth(-1))
df['b_new'] = df.a.replace(df.groupby('a').b.nth(-1))
df

   a   b  b_new
0  1  20     21
1  1  21     21
2  2  30     30
3  3  40     41
4  3  41     41
df.merge(df.drop_duplicates('a',keep='last'),on='a',how='left')
Out[797]: 
   a  b_x  b_y
0  1   20   21
1  1   21   21
2  2   30   30
3  3   40   41
4  3   41   41