当我使用groupby函数时,我无法正确插入缺失值。
这是我尝试过的一个简单示例:
import pandas as pd
import numpy as np
# Create data
state = pd.Series(['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'])
population = pd.Series([100, 150, np.nan, np.nan, 50, 125, np.nan, np.nan])
year = [2016, 2017, 2018, 2019, 2016, 2017, 2018, 2019]
dict = {'state': state, 'population': population, 'year': year}
df = pd.DataFrame(dict)
# Interpolate population, grouped by states
df.groupby('state').apply(lambda x: x.interpolate(method='linear'))
state population year
0 A 100.0 2016
1 A 150.0 2017
2 A 150.0 2018
3 A 150.0 2019
4 B 50.0 2016
5 B 125.0 2017
6 B 125.0 2018
7 B 125.0 2019
正如您所注意到的那样,当通过state
进行分组时,它只是重复最后一个值。
根据你的需要,传递方法spline
df.groupby('state')['population'].apply(lambda x : x.interpolate(method = "spline", order = 1, limit_direction = "both"))
0 100.0
1 150.0
2 200.0
3 250.0
4 50.0
5 125.0
6 200.0
7 275.0
Name: population, dtype: float64