Tanvi
Tanvi

Reputation: 69

How to loop through few lines

I have a doubt of how to loop over few lines :

get_sol is a function which is created which has two parameters : def get_sol(sub_dist_fil,fos_cnt)

banswara, palwai and hathin are some random values of a column named as "sub-district".

1 is fixed

I am writing it as :

out_1 = get_sol( "banswara",1)
out_1 = get_sol("palwal",1)
out_1 = get_sol("hathin",1)

How can I apply for loop to these lines in order to get results in one go

Help !!

"FEW COMMENTS HAVE HELPED ME IN ACHIEVING MY RESULTS (THANKS ALOT)". THE RESULT IS AS FOLLOW :

enter image description here NOW I HAVE A QUERY THAT HOW DO I DISPLAY/PRINT THE NAME OF RESPECTIVE DISTRICT FOR WHICH THE RESULTS ARE RUNNING???????

Upvotes: 0

Views: 94

Answers (4)

Shoham Debnath
Shoham Debnath

Reputation: 67

I think you are trying to get random values from the column 'subdistrict'

For the purpose of illustration, let the dataframe be df. (So to access 'subdistrict' column, df['subdistrict']

import numpy
[print(get_sol(x)) for x in np.random.choice(df['subdistrict'], 10)] 
# selecting 10 random values from particular columns 

Here is the official documentation

Upvotes: 0

Pac0
Pac0

Reputation: 23129

Similar other answers, but using a list comprehension to make it more pythonic (and faster, usually):

districts = ['banswara', 'palwal', 'hathin']
result = [get_sol(item, 1) for item in data]

Upvotes: 0

zipa
zipa

Reputation: 27869

Well in general case you can do something like this:

data = ['banswara', 'palwal', 'hathin']
result = {}

for item in data:
    result[item] = get_sol(item, 1)

print(result)

This will pack your results in dictionary giving you opportunity to see which result is generated for which input.

Upvotes: 1

alexzander
alexzander

Reputation: 1875

here you go:

# save the values into a list
random_values = column["sub-district"]

# iterate through using for
for random_value in random_values:

  # get the result
  result = get_sol(random_value, 1)

  # print the result or do whatever 
  # you want to the result
  print(result)

Upvotes: 0

Related Questions