15

Basic question on a pandas dataframe. I have a 1x1 dataframe with a datapoint and there are no column headers (currently). df[0,0] does not work because I think it is expecting a column name. In addition, df.0 doesn't work nor df[0,'']. df.ix[0,0] does work.

In general, am I required to have a column name? Is it a best practice to use column names with pandas dataframes? If my sql query does not have column headers, is it best to add them at that point?

Thanks for the help.

1 Answer 1

15

Nope, you're not required to assign column names, nor do you need them to access any element.

In [12]: df = pd.DataFrame([0])

In [13]: df.ix[0,0]
Out[13]: 0

In [14]: df[0][0]
Out[14]: 0

In fact, you can think of the column already having a name -- it is the integer 0. Look at what happens when you provide a name

In [15]: df    #Before naming the column
Out[15]:
   0
0  0

In [16]: df.columns = ['ColA']
In [17]: df    #Renamed
Out[17]:
   ColA
0     0

In [18]: df['ColA'][0]    #Now you can access the column using the new name
Out[18]: 0

In [19]: df[0][0]         #... but trying the old name will not work
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)

KeyError: 'no item named 0'

You can still use DataFrame.ix just as before, though:

In [20]: df.ix[0,0]
Out[20]: 0
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your help. Perhaps one other thing I should mention. When writing: In [1]: df Out[1]: 0 0 there is no "0" listed similar to your example with In[15]. Is that the issue I am running into? Thanks.
Perhaps you can show me using pastebin or by editing your question?
I'm sorry - don't know paste bin. But if you look at your example above for In[15] you have two rows of zeros. first row has one zero and the second has two zeros. In my example the first row is blank and the second row has two zeros.
Can show me how you created the dataframe? Are you using ipython in a terminal?
i used str = "select filename from equity_list where cusip = xxxx" filename = psql.frame_query(str, con = db) ##the db part should be working now. I have been running in a Unix terminal. My development is in Eclipse
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.