Performing for loop in pandas

Viewed 82

I have a CSV like the below:

i,ix,iz,iy,u'
0,1,1,1,-0.8696748576752853
1,1,1,2,2.3557976585107454
2,1,1,3,0.47209618683697663
3,1,1,4,-1.930481713597933
4,1,1,5,-1.7868247414530511
5,1,1,6,-0.5603642778861779
6,1,1,7,0.24540750240253573
7,1,1,8,0.5505270314521304
8,1,1,9,-0.1954277406567968
9,1,1,10,-1.3521265193776344

How to achieve values from u' when certain conditions are imposed in ix,iy,iz? For example, I would like to perform a for like the above:

for iy in list1:
    for iz in list2:
        for ix in list3:
           U = 2*df.iloc[a,4] ## `a` is just a row resulted from the the for's combination.

Furthermore, the whole CSV have 128^3 rows. This is the best way to perform loop in pandas? There's another faster way?

2 Answers

Generally, conditional statements can be written like this:

df[
  (df['ix'] == ix) &
  (df['iy'] == iy) &
  (df['iz'] == iz)
]["u'"]

In order to also iterate over the items in the mentioned lists, you can use itertools.product:

for ix, iy, iz in itertools.product(list1, list2, list3):
    output = df[
      (df['ix'] == ix) &
      (df['iy'] == iy) &
      (df['iz'] == iz)
    ]["u'"]

You can do this:

df[(df["ix"] == ix) & (df["iy"] == iy) & (df["iz"] == iz)]["u'"]

to get a Series of "u'" where its row meets your ix / iy / iz conditions. You would put this in your for loop if you had multiple ix / iy / iz conditions. Note that because there may be multiple rows that meet a particular condition, a Series is returned.

If you're only interested in a particular value (let's say the first if only one row is guaranteed to meet your particular condition), then you can index this Series with [0].

Though if it's a possibility that a condition has no matching rows at all, you would want to make sure the len of this Series is > 0 before indexing it.

Related