Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Column Names in pandas python

Tags:

python

pandas

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.

like image 411
user1911092 Avatar asked Dec 26 '12 20:12

user1911092


People also ask

How do you remove column names in python?

The most common way to remove a column is using df. drop() . Sometimes, del command in Python is also used.

How do you name a column with no name pandas?

The solution can be improved as data. rename( columns={0 :'new column name'}, inplace=True ) . There is no need to use 'Unnamed: 0' , simply use the column number, which is 0 in this case and then supply the 'new column name' . With Pandas 1.0.

How can I see column names in pandas?

You can get column names in Pandas dataframe using df. columns statement. Usecase: This is useful when you want to show all columns in a dataframe in the output console (E.g. in the jupyter notebook console).

How do I save a DataFrame without column names?

pandas to CSV without Header To write DataFrame to CSV without column header (remove column names) use header=False param on to_csv() method.


1 Answers

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
like image 125
Aman Avatar answered Oct 10 '22 02:10

Aman