Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set column names in pandas data frame from_dict with orient = 'index'

I looked already at this question: pandas create named columns in dataframe from dict. However, my example is slightly different.

I have a dictionary: my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}

And I created a pandas dataframe: df = pd.DataFrame.from_dict(my_dict, orient='index'), which is row oriented. However, when writing columns = ['one', 'two', 'three'] I get an error, as in the link above.

How do I name them?

like image 425
Euler_Salter Avatar asked Jul 03 '17 09:07

Euler_Salter


People also ask

How do I rearrange column names in Pandas?

Reorder Columns using Pandas . Another way to reorder columns is to use the Pandas . reindex() method. This allows you to pass in the columns= parameter to pass in the order of columns that you want to use.

What is Orient in Pandas?

orient: String value, ('dict', 'list', 'series', 'split', 'records', 'index') Defines which dtype to convert Columns(series into). For example, 'list' would return a dictionary of lists with Key=Column name and Value=List (Converted series).

How do you set a column to index in Pandas?

To create an index, from a column, in Pandas dataframe you use the set_index() method. For example, if you want the column “Year” to be index you type <code>df. set_index(“Year”)</code>. Now, the set_index() method will return the modified dataframe as a result.


2 Answers

Is there a reason you can't set the column names on the next line?

my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}
df = pd.DataFrame.from_dict(my_dict, orient='index')
df.columns = ['one', 'two', 'three']

Should work.

like image 65
LangeHaare Avatar answered Oct 10 '22 21:10

LangeHaare


From version 0.23.0, you can specify a columns parameter in from_dict:

my_dict = {'key1': [1, 2, 3], 'key2': [4, 5, 6], 'key3': [7, 8, 9]}
df = pd.DataFrame.from_dict(my_dict, orient='index', columns=['one', 'two', 'three'])
like image 34
Ninjakannon Avatar answered Oct 10 '22 20:10

Ninjakannon