Cohensius
Cohensius

Reputation: 545

Set values on the diagonal of pandas.DataFrame with fill_diagonal()

I want to set the values of the digonal in a pandas.df. I followed the answer in Set values on the diagonal of pandas.DataFrame

The solution of df.values[[np.arange(df.shape[0])] * 2] = 0 works fine.

But I wish to use np.fill_diagonal(df.values, 0) which gives AttributeError: 'DataFrame' object has no attribute 'flat'

Upvotes: 1

Views: 2169

Answers (1)

Nahko
Nahko

Reputation: 92

I had this problem too but solved it when I realised that np.fill_diagonal() works in-place.

np.fill_diagonal(df,0) gave me the AttributeError: you described and np.fill_diagonal(df.values,0) returns None so if you do something like:

df_zeros = np.fill_diagonal(df.values,0)
print(df_zeros)

or try to use the result elsewhere it won't work, but if you do:

np.fill_diagonal(df.values,0)
print(df)

I think you'll see what you're looking for.

Upvotes: 1

Related Questions