[英]Pandas Dataframe, change values on “diagonal” (where index-value is equal to column-name)
I have a pandas DataFrame, where the index is a subset of the columns, ie each value in the index is also a column-name and there are additional columns, so something like this: 我有一个pandas DataFrame,其中索引是列的子集,即索引中的每个值也是一个列名,还有其他列,所以像这样:
import pandas as pd
import numpy as np
df = pd.DataFrame(index=['John', 'Mary', 'Steven'],
columns=['John','Susan','Steven','Chris','Mary'],
data=np.arange(15).reshape(3,5))
I now want to set the "diagonal" items to a fixed value, say 0.0. 我现在想要将“对角线”项设置为固定值,比如说0.0。 By "diagonal" I mean those entries, where the index-value matches the column name.
“对角线”是指那些条目值与列名匹配的条目。 I can do it by iterating over the index and set each "diagonal" entry to 0.0 within that loop.
我可以通过迭代索引并在该循环中将每个“对角线”条目设置为0.0来实现。
for i in df.index:
df.loc[i, i] = 0.0
But I wonder if there was a more pythonic way, ie maybe a vectorized of achieving this. 但我想知道是否有更多的pythonic方式,也许是实现这一点的矢量化。 I'm thinking that there must be something like
df.loc[df.index, df.index] = 0.0
but that does not produce the desired results. 我认为必须有类似
df.loc[df.index, df.index] = 0.0
东西df.loc[df.index, df.index] = 0.0
不会产生预期的结果。
you can use the numpy's fill_diagonal function 你可以使用numpy的fill_diagonal函数
import numpy as np
#rearrange columns according to order of index
df = df.reindex(columns=list(df.index) + list(df.columns.difference(df.index)))
np.fill_diagonal(df.values,0)
print df
John Mary Steven Chris Susan
John 0 4 2 3 1
Mary 5 0 7 8 6
Steven 10 14 0 13 11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.