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?
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.
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).
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.
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.
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With