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)
Posted Sep 29, 2016, 8:58 PM UTC
The easiest solution is to access them like a dictionary:
Awesome that worked, what is different between what I did and what you did?
Python does not allow nonalphanumeric characters in attribute names. The parenthesis, for example, is reserved for executing a function. Therefore only column names that contain only alphanumerics and do not start with a number can be accessed as attributes.
However dictionary keys don't have any restrictions on the string.
I see, I just realized that both of my graphs were being graphed againts time. Which I don't want to always do that. So I tried this:
however, I am getting invlade syntax even if I tried the ["Accel_Y(g)"] method.
"invalid syntax" often means you forgot to close a parenthesis on the previous line.
If not, show us the complete code you are using and the complete error message. I don't see anything wrong with that snippet.
You were accessing columns like an attribute, df.column. They can also be accessed like a dict, df['column']. Note the quotes, square brackets and lack of period.