Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute access on invalidly named columns

Tags:

pandas

Using Pandas 0.11.0, I am trying to read in data from a CSV file with the following structure:

Date/Time   Data1    Data2
  5/10/13      23     17.0
  5/10/14      20     17.1
  5/10/15      27     17.3

In order to create a new column based on existing data, I would use attribute access of the fashion:

df["Result"] = 2.0 * df.Data2

However, because "Date/Time" is not a valid attribute name, what is the recommended way to create a new column based on the data in the "Data/Time" column? I would prefer not to have to manually specify all column names when using the read_csv method.

like image 297
superlou Avatar asked Mar 12 '26 07:03

superlou


1 Answers

Use df['Date/Time']. The attribute access style of selecting a column, df.column_name, is merely a convenient shortcut for df['column_name']. It is simply not possible to use this convenience when your column names are not valid Python identifiers, as in 'Date/Time'. You can change the name, or you can use the long form.

like image 103
Dan Allan Avatar answered Mar 14 '26 03:03

Dan Allan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!