将For语句向量化 – 对角线上的零

huangapple go评论57阅读模式
英文:

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) 

huangapple
  • 本文由 发表于 2023年5月22日 09:21:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定