Python Forum
How to access dataframe elements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to access dataframe elements
#1
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]
Reply
#2
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.
Reply
#3
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.
Reply
#4
temp=str(df.values[i, j])
??
Reply
#5
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Formula with elements of list - If-condition regarding the lists elements lewielewis 2 2,702 May-08-2020, 01:41 PM
Last Post: nnk
  Index in Python list contains multiple elements.How to access each val and pass them Shameendra 1 2,392 Nov-30-2018, 05:41 PM
Last Post: wavic
  Checking the elements of a matrix with an elements of a list juniorcoder 11 5,758 Sep-17-2018, 03:02 PM
Last Post: gruntfutuk
  access a very large file? As an array or as a dataframe? Angelika 5 4,861 May-18-2017, 08:15 AM
Last Post: Angelika

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020