Doc Doc - 2 months ago 6
Python Question

Python DataFrame error for having a header with parenthesis

I am very new to python and programming in general. I have a CSV file that has the first column as string headers.

ie

time, speed(m/s), distance(m)
2,6,20
3,2,10

etc..


What I am trying to do is a program that will spit out a bunch of graphs based on my selection. for example time vs speed. or time vs speed and distance.

My first issue is whenever I try to graph something that has a parenthesis in its name for example:

df.Accel_Y(g).plot(color='r',lw=1.3)


I receive an error of:


AttributeError: 'DataFrame' object has no attribute 'Accel_Y'


It works fine if I try with a different column that has no parenthesis.

I tried to assign accel_y(g) to a letter for example z. Then doing this:

f.z.plot(color='r',lw=1.3)


that also didn't work.

Here is my code:

import pandas as pd
from pandas import DataFrame, read_csv
import numpy as np
import matplotlib.pyplot as plt


df = pd.DataFrame.from_csv('Flight102_Complete.csv')
df.KestrelTime.plot(color='g',lw=1.3)
df.Accel_Y(g).plot(color='r',lw=1.3)
print (df)

Answer

You should consider that accessing your columns via the . (dot) operator a privileged convenience. It can break under many circumstances and sometimes silently so. If you want to access the column do so with [] or loc[] or iloc[].

Parenthesis are one of the conditions that will break the . accessor paradigm.

In your case
Don't do

df.Accel_Y(g).plot(color='r', lw=1.3)

Instead do

df['Accel_Y(g)'].plot(color='r', lw=1.3)
Comments