1

I am pivoting a dataframe.

df_features = df_features.pivot(index='filename', columns='code', values='frequency')

but when I do so the index field which is filename gets missing!

my dataframe is like this

filename  code  frequency
F1         X1       3      
F1         X2       6        
F1         X3       4
F2         X1       7
F2         X4       9
F3         X2       1
F3         X3       5
F4         X1       3
F4         X3       4
F4         X4       3
F5         X3       2

after Pivoting It should look like this

filename  X1   X2   X3   X4
F1        3    6    4    0
F2        7    0    0    9
F3        0    1    5    0
F4        3    0    4    3
F5        0    0    2    0

But what I acually Get is

X1   X2   X3   X4
3    6    4    0
7    0    0    9
0    1    5    0
3    0    4    3
0    0    2    0

my question is how to include filename in the pivoted dataframe?

Edit :

This is how the data look like in another example after pivoting

enter image description here

alothough I can see file name in the columns!!! yet when I try this code I get error

df_features["filename" ]


KeyError: 'filename'

1 Answer 1

2

Your filename "key" is no longer a key, but an index.

for i in df_features.index: print (i)

This will give you your filenames. Does this help?

Sign up to request clarification or add additional context in comments.

5 Comments

when i export the dataframe to a csv file there is no key or index !
Try the following: df_features.to_csv('test.csv', index=True, index_label='filename')
is there anyway I can keep filename as is in the dataframe after pivot
This is what I get from your original dataframe: $ cat test.csv filename,X1,X2,X3,X4 F1,3.0,6.0,4.0,0.0 F2,7.0,0.0,0.0,9.0 F3,0.0,1.0,5.0,0.0 F4,3.0,0.0,4.0,3.0 F5,0.0,0.0,2.0,0.0
The comments leave something to be desired with respect to formatting. Imagine each comma-delimited list that begins with F1, F2, etc. as a new line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.