假设我们有一个using UnityEngine;
using GoogleMobileAds.Api;
public class ads : MonoBehaviour
{
bool called = false;
void Start()
{
if (Application.loadedLevelName == "gameplay")
{
interesRequest(called);
}
if (Application.loadedLevelName == "mainMenu")
{
bannerRequest();
}
if (Application.loadedLevelName == "levelScore")
{
}
}
void bannerRequest()
{
BannerView bannerView = new BannerView("ca-app-pub-5443208681329246/6087569010", AdSize.Banner, AdPosition.Bottom);
AdRequest request = new AdRequest.Builder().Build();
bannerView.LoadAd(request);
bannerView.Show();
}
void interesRequest(bool call)
{
InterstitialAd inters = new InterstitialAd("ca-app-pub-5443208681329246/7564302219");
if (call)
{
if (inters.IsLoaded())
{
inters.Show();
called = false;
}
}
else
{
AdRequest request = new AdRequest.Builder().Build();
inters.LoadAd(request);
}
}
void Update()
{
if (called)
interesRequest(called);
}
public void OnMouseDown()
{
if (gameObject.name == "pause")
{
if (menu.bug)
{
called = true;
}
}
}
数据集:
test
现在我们想用value group
123 1
120 1
NA 1
130 1
23 2
22 2
24 2
NA 2
替换缺失值 - 明智的中值。在group
中,我们可以使用嵌套的R
调用来完成此操作。
ifelse
我虽然将first.med <- median(test[test$group == 1, ]$value, na.rm = T)
second.med <- median(test[test$group == 2, ]$value, na.rm = T)
test$value <- ifelse(is.na(test$value) & test$group == 1, first.med
ifelse(is.na(test$value) & test$group == 2, second.med,
test$value))
函数或numpy.where
方法应用为showcased here,但这两种技术都不支持嵌套。我可以想到列表理解来做到这一点,但我想知道在NumPy / pandas领域是否有替代品。提前谢谢。
答案 0 :(得分:3)
在这种情况下,您可以使用groupby
填充组中位数:
In [16]: df.groupby('group')['value'].apply(lambda x: x.fillna(x.median()))
Out[16]:
0 123
1 120
2 123
3 130
4 23
5 22
6 24
7 23
dtype: float64
虽然一般来说,这两种方法都可以嵌套得很好。例如,你可以这样做:
In [23]: medians = df.groupby('group')['value'].median()
In [24]: np.where(pd.isnull(df['value']),
np.where(df['group'] == 1, medians.loc[1], medians.loc[2]),
df['value'])
Out[24]: array([ 123., 120., 123., 130., 23., 22., 24., 23.])
答案 1 :(得分:1)
df = pd.DataFrame({'value' : [123,120,np.nan ,130,23 ,22 ,24 ,np.nan] , 'group' : [1 , 1 ,1 , 1 , 2 , 2 , 2 , 2] })
def replace_with_median(df):
df['value'][pd.isnull(df['value'])] = df['value'].median()
return df
df.groupby('group').apply(replace_with_median)