'Selecting data from a pandas DataFrame

I have defined a pandas DataFrame, given the number of rows (index) and columns. I perform a series of operations and store the data in such DataFrame. The code that makes this operation is the next one:

import math
import numpy as np
import pandas as pd

sens_fac = [0.8, 1, 1.2]

A = 13;
B = 5;
C = 7/2;
D = 3*1.2;
par = [A,B,C,D]
data = pd.DataFrame(index=range(len(sens_fac)),columns=range(len(par)))

for i in range(len(par)):
    factors = [1, 1, 1, 1]
    for j in range(len(sens_fac)):
        factors[i] = sens_fac[j]
        print(factors)
        x=25
        t1 = np.log(x)**math.sin(x/(A*factors[0]))
        t2 = (B*factors[1])*math.sqrt(x)
        t3 = (factors[2]*C)**math.exp(1/x)
        t4 = x/(factors[3]*D)*2
        res = t1 + t2 + t3 + t4
        data[i][j] = res

The problem is when I try to select a specific element of such DataFrame. For example, if I print data, it would be a DataFrame of 3 rows and 4 columns. But when I try to select the element of the third row and fourth column (data[2][3]), I get an error. On the other hand, if I select the element asdata[3][2], it gives me the number I am looking for, but I understand that data[3][2] would be the fourth row and third column, which is an element that does not exist.



Solution 1:[1]

The data frame values can be accessed using explicit indexing(loc), implicit indexing (iloc). To be more clear: suppose column 3 has the name 'qwe', and the index of row 2 will be 'c'. This is called explicit reference to indexes.

data.loc['c', 'qwe']

Implicitly , you can apply like this:

data.iloc[2, 3]

But, if you will use a slice. Then with explicit indexing, there will be one more value, since with explicit indexing, the slice occurs inclusive.

print(data.loc[:2, 3])
print(data.iloc[:2, 3])
"""
0    49.0406
1    45.5684
2    43.2536
Name: 3, dtype: object
0    49.0406
1    45.5684
Name: 3, dtype: object
"""

Since you have indexes (rows) in strict numbering, using an explicit and implicit index will lead to the same result.

print(data.loc[2, 3])#43.2535547215997
print(data.iloc[2, 3])#43.2535547215997

iloc, loc and at, iat the difference is described here

For single values, it is assumed that faster at, iat.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1