Let's say: I have dataframe like this:
import pandas as pd
df = pd.DataFrame({'a':['a1','a2','a3','a4','a5'],'b':[1,2,3,4,5]})
Output:
a b
0 a1 1
1 a2 2
2 a3 3
3 a4 4
4 a5 5
Now I would like to add new columns corresponding to a1
, a2
, a3
, a4
, a5
for index, row in df.iterrows():
df[index] = np.NaN
Output:
a b 0 1 2 3 4
0 a1 1 NaN NaN NaN NaN NaN
1 a2 2 NaN NaN NaN NaN NaN
2 a3 3 NaN NaN NaN NaN NaN
3 a4 4 NaN NaN NaN NaN NaN
4 a5 5 NaN NaN NaN NaN NaN
How can I generate a triangular matrix in the dataframe?
I would like the following output:
a b 0 1 2 3 4
0 a1 1 a1 a2 a3 a4 a5
1 a2 2 NaN a2 a3 a4 a5
2 a3 3 NaN NaN a3 a4 a5
3 a4 4 NaN NaN NaN a4 a5
4 a5 5 NaN NaN NaN NaN a5
Should I build one extra dataframe as a triangular matrix and then merge? What is the easiest way?