我想在Python中编写一个函数,它根据输入索引的值返回不同的固定值.
在其他语言中,我会使用switch或case声明,但Python似乎没有switch声明.在这种情况下,推荐的Python解决方案是什么?
我有一个相对较大的DataFrame对象(大约一百万行,数百列),我想按组剪切每列中的异常值.通过"按组分组每个列的异常值"我的意思是 - 计算组中每列的5%和95%分位数,并剪切该分位数范围之外的值.
这是我目前正在使用的设置:
def winsorize_series(s):
q = s.quantile([0.05, 0.95])
if isinstance(q, pd.Series) and len(q) == 2:
s[s < q.iloc[0]] = q.iloc[0]
s[s > q.iloc[1]] = q.iloc[1]
return s
def winsorize_df(df):
return df.apply(winsorize_series, axis=0)
Run Code Online (Sandbox Code Playgroud)
然后,通过我的DataFrame调用features和索引DATE,我可以做到
grouped = features.groupby(level='DATE')
result = grouped.apply(winsorize_df)
Run Code Online (Sandbox Code Playgroud)
这是有效的,除了它非常慢,可能是由于嵌套apply调用:每个组一个,然后每个组中的每个列一个.我试图apply通过一次计算所有列的分位数来摆脱第二个,但是试图将每个列的阈值设置为不同的值.有没有更快的方法来完成此过程?
我从sklearn网站上获取了示例代码
tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000]},
{'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]
scores = [('f1', f1_score)]
for score_name, score_func in scores:
print "# Tuning hyper-parameters for %s" % score_name
print
clf = GridSearchCV( SVC(), tuned_parameters, score_func=score_func, n_jobs=-1, verbose=2 )
clf.fit(X_train, Y_train)
print "Best parameters set found on development set:"
print
print clf.best_estimator_
print
print "Grid scores on development set:"
print
for params, mean_score, scores in clf.grid_scores_:
print "%0.3f (+/-%0.03f) for %r" % …Run Code Online (Sandbox Code Playgroud) 我有一个数据框:
Time Weight
1 4
2 2
3 1
4 7
Run Code Online (Sandbox Code Playgroud)
如何标准化权重列,使权重列中的值之和等于 1 ?
我试图将数据帧中的每个值绑定在0.01和0.99之间
我使用以下方法成功地将0到1之间的数据标准化:.apply(lambda x: (x - x.min()) / (x.max() - x.min()))如下:
df = pd.DataFrame({'one' : ['AAL', 'AAL', 'AAPL', 'AAPL'], 'two' : [1, 1, 5, 5], 'three' : [4,4,2,2]})
df[['two', 'three']].apply(lambda x: (x - x.min()) / (x.max() - x.min()))
df
Run Code Online (Sandbox Code Playgroud)
现在我想绑定0.01到0.99之间的所有值
这是我尝试过的:
def bound_x(x):
if x == 1:
return x - 0.01
elif x < 0.99:
return x + 0.01
df[['two', 'three']].apply(bound_x)
Run Code Online (Sandbox Code Playgroud)
df
但是我收到以下错误:
ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', …Run Code Online (Sandbox Code Playgroud) 我正在使用以下代码规范化熊猫数据框:
df_norm = (df - df.mean()) / (df.max() - df.min())
Run Code Online (Sandbox Code Playgroud)
当所有列都是数字时,这可以正常工作。但是,现在我有一些字符串列,df并且上面的规范化出现了错误。有没有一种方法只能在数据帧的数字列上执行这种规范化(保持字符串列不变)?谢谢!