1

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'

Cohensius
  • 385
  • 7
  • 18
  • For me it working nice with sample data `df = pd.DataFrame(np.random.rand(5,5))`, what is your pandas version? – jezrael Oct 11 '18 at 08:28
  • 0.22.0, I will try to upgrade and see if it solves the problem – Cohensius Oct 11 '18 at 08:34
  • 1
    I just check linked solution and working in 2014 year, so problem is something else :( – jezrael Oct 11 '18 at 08:36
  • I could not upgrade to pandas 0.23.4 since I am not the admin of the computer. Pyton3 is installed only on my user and not as admin, could that cause the problem somehow? – Cohensius Oct 11 '18 at 11:39
  • tryied to use your sample data `df = pd.DataFrame(np.random.rand(5,5))` and I still get that error – Cohensius Oct 11 '18 at 11:41
  • hmmm, not idea. only idea is use `arr = df.values`, `df = pd.DataFrame(np.fill_diagonal(arr, 0), index=df.index, columns=df.columns)` - working with numpy array. – jezrael Oct 11 '18 at 11:42

1 Answers1

1

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.

Nahko
  • 78
  • 10