我想使用 groupby.first() 函数来查找组的第一个非空值并将该值转换为组中的每一行。
我尝试了以下代码:
import pandas as pd
import numpy as np
raw_data = {'col1': ['a','a','a','b','b','b','b','b','b','c','c','c','c','c'],
'col2': [np.nan,np.nan,6,0,2,0,8,2,2,3,0,0,4,5]}
df=pd.DataFrame(raw_data)
df['col3'] = df.groupby('col1')['col2'].transform(lambda x: x.first())
df
Run Code Online (Sandbox Code Playgroud)
我想得到一个看起来像这样的 df:
col1 col2 col3
a NaN 6
a NaN 6
a 6 6
b 0 0
b 2 0
b 0 0
b 8 0
b 2 0
b 2 0
c 3 3
c 0 3
c 0 3
c 4 3
c 5 3
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:TypeError: first() missing 1 required positional argument: 'offset' …