Python Forum

Full Version: How to access dataframe elements
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I have below dataframe:

HAY 12/3  2019-07-07 5
KOP Pass  2019-07-10 ok
GHK 1/4   2019-07-11 8/3
I want to loop through columns and rows and access each cell element.
For example, df[1,2] show give me 2019-07-10
df[0,1] -->12/3 etc

I use the below code but it gives me whole row

for i,j in df.iterrows():
        dt=df.ix[i,j]
If you want to iterate over all values of the df, you can do the following:

m, n = df.values.shape
for i in range(m):
    for j in range(n):
        print(df.values[i, j])
df.iterrows() returns value of the index and the current row.
Usually, there is no need to use raw python loops when working with pandas. Pure python loops
are slow.
But some of the value is becoming "int", in fact, I need all the values to be "str". May be is it because of df.values? I use
temp=df.values[i, j].str()
but it does not work.
temp=str(df.values[i, j])
??
You can convert your data to string at once, e.g.:

df.values.astype(str)[i, j]
As I mentioned above, if you need to use loops
when working with pandas and doing some data processing, it is likely
something wrong. Pandas was specially designed to avoid pure python loops when possible because they
are quite slow.