示例df:
data = pd.DataFrame({'col1': ['1.55', '2.22', '2.22', '3.33'],
'col2': ['10', '15', '20', '30']})我想在col1上添加一个使用数学函数的新列。
data['new'] = math.radians(data['col1'])或
data['new'] = math.tan(data['col1'])这给了我错误TypeError: cannot convert the series to <class 'float'>。我已经使用col1将data['col1'] = data['col1'].astype(float64)转换为浮动,所以我认为错误肯定是因为data['new']不能转换为浮点数。
我如何解决这个问题,并使用math从旧列创建新的数据格式列?如果能解释一下为什么math没有很好地处理数据格式,那就太好了。
发布于 2019-07-10 00:05:42
有两种方法可以解决您的问题,因为您希望将标量值传递给您的数学函数:
方法1使用.astype和.apply
data['new'] = data['col1'].astype(float).apply(math.radians)
col1 col2 new
0 1.55 10 0.027053
1 2.22 15 0.038746
2 2.22 20 0.038746
3 3.33 30 0.058119方法2(更快的方法)是使用numpy函数
numpy以数组作为输入。
data['new2'] = np.tan(data['col1'].astype(float))
col1 col2 new new2
0 1.55 10 0.027053 48.078482
1 2.22 15 0.038746 -1.317612
2 2.22 20 0.038746 -1.317612
3 3.33 30 0.058119 0.190669发布于 2019-07-09 23:57:53
首先,不要把你的数字数据帧元素括在“引号”中。
data = pd.DataFrame({'col1': [1.55, 2.22, 2.22, 3.33],
'col2': [10, 15, 20, 30]})如果数据就是这样提供给您的,那么使用.astype函数。
data['col1'] = data['col1'].astype(float)在数据帧上执行操作时,请使用apply()。
data['new'] = data['col1'].apply(math.tan)当然,通过执行以下代码可以同时完成所有这些工作:
data['new'] = data['col1'].astype(float).apply(math.tan)https://stackoverflow.com/questions/56961724
复制相似问题