I want to assign values to the diagonal of a dataframe. The fastest way I can think of is to use numpy's np.diag_indices and do a slice assignment on the values array. However, the values array is only a view and ready to accept assignment when a dataframe is of a single dtype
Consider the dataframes d1 and d2
d1 = pd.DataFrame(np.ones((3, 3), dtype=int), columns=['A', 'B', 'C'])
d2 = pd.DataFrame(dict(A=[1, 1, 1], B=[1., 1., 1.], C=[1, 1, 1]))
d1
A B C
0 0 1 1
1 1 0 1
2 1 1 0
d2
A B C
0 1 1.0 1
1 1 1.0 1
2 1 1.0 1
Then let's get our indices
i, j = np.diag_indices(3)
d1 is of a single dtype and therefore, this works
d1.values[i, j] = 0
d1
A B C
0 0 1 1
1 1 0 1
2 1 1 0
But not on d2
d2.values[i, j] = 0
d2
A B C
0 1 1.0 1
1 1 1.0 1
2 1 1.0 1
I need to write a function and make it fail when df is of mixed dtype. How do I test that it is? Should I trust that if it is, this assignment via the view will always work?
d1.dtypeswhich is aSeriesitself, and you check if all have the same value.d2.dtypes.nunique()>1?