我有一个名为df4的df,您可以购买以下代码:
df4s = """
contract RB BeginDate ValIssueDate EndDate Valindex0 48 46 47 49 50
2 A00118 46 19850100 19880901 99999999 50 1 2 3 7 7
3 A00118 47 19000100 19880901 19831231 47 1 2 3 7 7
5 A00118 47 19850100 19880901 99999999 50 1 2 3 7 7
6 A00253 48 19000100 19820101 19811231 47 1 2 3 7 7
7 A00253 48 19820100 19820101 19841299 47 1 2 3 7 7
8 A00253 48 19850100 19820101 99999999 50 1 2 3 7 7
9 A00253 50 19000100 19820101 19781231 47 1 2 3 7 7
10 A00253 50 19790100 19820101 19841299 47 1 2 3 7 7
11 A00253 50 19850100 19820101 99999999 50 1 2 3 7 7
"""
df4 = pd.read_csv(StringIO(df4s.strip()), sep='\s+',
dtype={"RB": int, "BeginDate": int, "EndDate": int,'ValIssueDate':int,'Valindex0':int})
结果是:
contract RB BeginDate ValIssueDate EndDate Valindex0 48 46 47 49 50
2 A00118 46 19850100 19880901 99999999 50 1 2 3 7 7
3 A00118 47 19000100 19880901 19831231 47 1 2 3 7 7
5 A00118 47 19850100 19880901 99999999 50 1 2 3 7 7
6 A00253 48 19000100 19820101 19811231 47 1 2 3 7 7
7 A00253 48 19820100 19820101 19841299 47 1 2 3 7 7
8 A00253 48 19850100 19820101 99999999 50 1 2 3 7 7
9 A00253 50 19000100 19820101 19781231 47 1 2 3 7 7
10 A00253 50 19790100 19820101 19841299 47 1 2 3 7 7
11 A00253 50 19850100 19820101 99999999 50 1 2 3 7 7
我试图通过以下逻辑构建一个新列,新列的值将基于2个现有列的值:
def test(RB):
n=1
for i in np.arange(RB,50):
n = n * df4[str(i)].values
return n
vfunc=np.vectorize(test)
df4['n']=vfunc(df4['RB'].values)
然后收到错误:
res = array(outputs, copy=False, subok=True, dtype=otypes[0])
ValueError: setting an array element with a sequence.
重建数据帧(感谢使用
StringIO
方法)请注意完整的回溯
vectorize
从这组混合大小的数组创建返回数组时遇到问题。它“猜出了, based on a trial calculation that it should return an
int`dtype如果我们告诉它返回一个对象数据类型数组,我们得到:
我们可以将其分配给df列:
我们也可以分配
Out[85]
列表时间差不多:
通常
vectorize
比较慢,但test
本身可能足够慢,迭代方法也没有多大区别。请记住(如有必要,请重新阅读文档),vectorize
不是性能工具。它不会“编译”您的函数或使其运行更快返回对象数据类型数组的替代方法:
相关问题 更多 >
编程相关推荐