Python Forum
How to access dataframe elements - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: How to access dataframe elements (/thread-20070.html)



How to access dataframe elements - SriMekala - Jul-26-2019

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]



RE: How to access dataframe elements - scidam - Jul-26-2019

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.


RE: How to access dataframe elements - SriMekala - Jul-26-2019

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.


RE: How to access dataframe elements - fishhook - Jul-26-2019

temp=str(df.values[i, j])
??


RE: How to access dataframe elements - scidam - Jul-30-2019

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.