-1

so i have a

df = read_excel(...)

loop does work:

for i, row in df.iterrows(): #loop through rows
    a = df[df.columns].SignalName[i] #column "SignalName" of row i, is read
    b = (row[7]) #column "Bus-Signalname" of row i, taken primitively=hardcoded

Access to a is ok, how to replace the hardcoded b = (row[7]) with a dynamically found/located "Bus-Signalname" element from the excel table. Which are the many ways to do this?

 b = df[df.columns].Bus-Signalname[i]

does not work.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • https://stackoverflow.com/questions/13757090/pandas-column-access-w-column-names-containing-spaces – Shijith Aug 24 '20 at 10:52

2 Answers2

0

To access the whole column, run: df['Bus-Signalname']. So called attribute notation (df.Bus-Signalname) will not work here, since "-" is not allowed as a part of an attribute name.

It is treated as minus operator, so:

  • the expression before it is df.Bus, but df probably has no column with whis name, so an exception is thrown,
  • what occurs after it (Signalname) is expected to be e.g. a variable, but you probably have no such variable and this is another reason which could cause an exception.

Note also that then you wrote [i]. As I understand, i is an integer and you want to access element No i from this column.

Note that the column you retrieved is a Series with index just the same as your whole DataFrame.

If the index is a default one (consecutive numbers, starting from 0), you will succeed. Otherwise (if the index does not contain value of i) you will fail.

A more pandasonic syntax to access an element in a DataFrame is:

df.loc[i, 'Bus-Signalname']

where i is the index of the row in question and Bus-Signalname is the column name.

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
0

@Valdi_Bo

thank you. In the loop, both

df.loc[i, 'Bus-Signalname'] 

and

df['Bus-Signalname'][i]

work.