英文:
Vectorize a For Statement - Zeros In A Diagonal
问题
想要用一个向量化的理解语句替换Python中的'for'循环,将pandas DataFrame
的左对角线替换为零。
DataFrame
是使用标准的 numpy.random.randint()
方法实例化的。
df = pd.DataFrame(np.random.randint(1, 100, 100).reshape(10, -1))
我尝试应用一个lambda函数,使用df.iloc[]
方法定位/替换对角线上的单元格。期望左对角线被替换为零。
df = df.apply(lambda i: [df.iloc[i, i] * 0 for i in range(df.shape[0])])
结果是整个DataFrame
被加载为零。需要帮助来编写lambda函数,因为lambda函数中不允许赋值。
英文:
Want to replace a Python 'for' loop with a vectorized comprehension statement to replace the left diagonal in a pandas DataFrame
with zeroes.
The dataframe
is instantiated using a standard numpy.random.randint()
method.
df = pd.DataFrame(np.random.randint(1,100, 100).reshape(10, -1))
I tried to apply a lambda function that locates/replaces the diagonal cells using the df.iloc[]
method. Was expecting the left diagonal to be replaced with zeroes.
df = df.apply(lambda i : [df.iloc[i, i] * 0 for i in range(df.shape[0])])
The result yields an entire DataFrame
loaded with zeroes. Need help on how to write the lambda function since an assignment is not allowed in the lambda function.
答案1
得分: 1
如果您使用 iloc
,您将不会得到一个矢量化的函数,因为您实际上是在遍历索引。
相反,您应该使用NumPy自己的fill_diagonal()
方法
arr = np.random.randint(1, 100, 100).reshape(10, -1)
np.fill_diagonal(arr, 0)
df = pd.DataFrame(arr)
英文:
If you use iloc
you won't get a vectorized function since you're essentially iterating over indices.
What you should do instead is to use NumPy's own fill_diagonal()
method
arr = np.random.randint(1,100, 100).reshape(10, -1)
np.fill_diagonal(arr, 0)
df = pd.DataFrame(arr)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论