1 回答

TA貢獻1906條經(jīng)驗 獲得超3個贊
使用DataFrame.assign
for reasign 將不匹配的值替換為NaN
中的 s?Series.where
:
df1 = (df.assign(animal = df['animal'].where(df['animal'] == 'cat'),
? ? ? ? ? ? ? ? ?height = df['height'].where(df['height'] > 10),
? ? ? ? ? ? ? ? ?from1 = df['from'].where(df['from'] == 'breeder')
? ? ? ? ? ? ? ? )
? ? ? ? .groupby(['Person']).agg(
? ? ? ? ? ? ? ? ?number_of_animal = pd.NamedAgg(column = 'animal', aggfunc = 'count'),
? ? ? ? ? ? ? ? ?number_of_from = pd.NamedAgg(column = 'from1', aggfunc = 'count'),
? ? ? ? ? ? ? ? ?total_height = pd.NamedAgg(column = 'height', aggfunc = 'sum'),
? ? ? ? ? ? ? ? ?total_weight = pd.NamedAgg(column = 'weight', aggfunc = 'sum')
? ? ))
print (df1)
? ? ? ? number_of_animal? number_of_from? total_height? total_weight
Person? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
John? ? ? ? ? ? ? ? ? ?2? ? ? ? ? ? ? ?1? ? ? ? ? ?0.0? ? ? ? ? 17.8
Paul? ? ? ? ? ? ? ? ? ?0? ? ? ? ? ? ? ?1? ? ? ? ? 34.0? ? ? ? ?205.5
Taylor? ? ? ? ? ? ? ? ?0? ? ? ? ? ? ? ?0? ? ? ? ? 55.0? ? ? ? ?200.0
添加回答
舉報