Convert a single row to a sparse matrix of NaNs with pandas

Viewed 231

Given a dataframe of the form:

   col1  col2  col3  col4
0     1     2     3     4

I want to move each element at position [0, i] in the current dataframe to position [i, i] in the new one. So, for this input, my desired output will be:

   col1   col2  col3  col4    
0   1.0    NaN   NaN   NaN
1   NaN    2.0   NaN   NaN
2   NaN    NaN   3.0   NaN
3   NaN    NaN   NaN   4.0

Note that the position has nothing to do with the values of the elements themselves.

I know I can do this with numpy by calling np.diag, but that returns a 2D array of 0s, and I cannot replace 0s with NaNs, because some of the diagonal values might also be replaced, if they are also 0s.

What's the simplest way to do this with pandas?

5 Answers

IIUIC, you could use a comprehension generator.

In [1115]: df
Out[1115]:
   col1  col2  col3  col4
0     1     2     3     4

In [1116]: pd.DataFrame({c: v} for c, v in df.iloc[0].items())
Out[1116]:
   col1  col2  col3  col4
0   1.0   NaN   NaN   NaN
1   NaN   2.0   NaN   NaN
2   NaN   NaN   3.0   NaN
3   NaN   NaN   NaN   4.0
Related