我正在尝试合成一组数据。我使用的是python3.5.2。我首先将其定义为:
#Make Synthetic data (great again?)
#synth X
data=pd.DataFrame(np.random.randn(100,5), columns= 'x1','x2','x3','x4','x5'])
def div10(x):
if x<0:
return -x/5
else:
return x/10
data=data.applymap(div10)
从这里开始,我想定义一个新列,如果行中Xs平均值的双曲正切大于.15,则为字符串'dead',否则为'alive:
^{pr2}$我被告知ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0')
当我检查np.tanh(data.mean(axis=1))>.15
时,我得到了一份酒精清单。在
我也试过地图,但是AttributeError: 'DataFrame' object has no attribute 'map'
学习使用where语句来获得更好更快的代码。在
让我们把它分成块。where语句可以对多维数据(如您拥有的dataframe)进行操作。它们接受一个条件,当为true时返回逗号后的第一个参数,当为false时返回第二个参数
^{pr2}$不需要使用
apply
,因为numpy有一个可以按行应用的向量化平均函数(axis=1)现在你有了一维数据。取双曲正切
最后使用另一个where语句来获取dead或alive条件
您需要确保使用的是lambda函数中指定的“x”。另外,由于x是一个序列(数据帧中的行),axis=1不起作用。
data['Y']=data.apply(lambda x:'dead' if np.tanh(x.mean())>.15 else 'alive',axis=1)
相关问题 更多 >
编程相关推荐