我有一个数据帧,其中一些值是NA。我想删除NA,并用可用数据的数据替换它们。
这就是数据帧的样子-
<dataframe: flowers>
type pedals depth height
iris 4 NA NA
iris NA 3 NA
iris NA NA 8
sunflow NA 5 NA
sunflow NA NA 13
sunflow 12 NA NA
poppie 1 NA NA
poppie NA 2 NA
这就是我要做的事情-
<dataframe: flowers>
type pedals depth height
iris 4 3 8
sunflow 12 5 13
poppie 1 2 NA
首先,您需要将NaN替换为零,然后您可以通过和进行分组。
df = df.fillna(0)
final_df = df.groupby('type').sum()
由于NaN值为零,因此对于给定类型的所有行,总和将仅取唯一的非零值。