Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

python - Setting value in very first cell in pandas dataframe

in my Python script I'm initializing a dictionary which will be managed afterwards as a nested dictionary. After updating and working with it I want to save it as a csv file as a permanent storage so I can read it in again later and then update again and so on.

My problem is the following. For working with the nested dictionary it has the following structure:

dict = {
    'key1': {
        'grp1': 0,
        'grp2': 2
    }
}

Using pandas I can perfectly export this as a csv file using data = pd.DataFrame(dict) which I can then use as a table in Libre Calc or Excel where it looks like this:

key
grp1 2
grp2 4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use:

df = pd.DataFrame({'key1': {'grp1': 0,
                            'grp2': 2
                           }
                  })


df.reset_index().rename(columns={'index':'your_value'})
    your_value  key1
0   grp1        0
1   grp2        2

And when you save the file using df.to_csv() pass index=False and you won't have those 0 and 1 indexes in the very left.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...