1

I wish to read pandas DataFrame element by element, but it seems below code doesn't work!

import pandas as pd

df = pd.DataFrame()
df1 = pd.DataFrame({"A": [2,3,4]})
df2 = pd.DataFrame({"B": [5,6,7]})
df = pd.concat([df1, df2], axis=1)

for row in df.iterrows():
    print row['A'], row['B']

What's the right way to access it element by element?

1
  • Do you just want to print it or actually DO something with it or to it? E.g. if you want to apply a function to every element, see applymap() Commented Apr 23, 2015 at 20:52

3 Answers 3

1

Use at and iat detailed here

Since indexing with [] must handle a lot of cases (single-label access, slicing, boolean indexing, etc.), it has a bit of overhead in order to figure out what you’re asking for. If you only want to access a scalar value, the fastest way is to use the at and iat methods, which are implemented on all of the data structures.

Similarly to loc, at provides label based scalar lookups, while, iat provides integer based lookups analogously to iloc

Sign up to request clarification or add additional context in comments.

Comments

0

How about this one:

import pandas as pd

df = pd.DataFrame()
df1 = pd.DataFrame({"A": [2,3,4]})
df2 = pd.DataFrame({"B": [5,6,7]})
df = pd.concat([df1,df2], axis=1)

for row in df.index:
    print df['A'][row],df['B'][row]

Output:

2 5
3 6
4 7

Comments

0

In this case, the following works with iterrows:

>>> for _, row in df.iterrows():
        print row.A, row.B
2 5
3 6
4 7

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.