Q:

Write within-patient data from single observation to multiple text files

I am trying to write individual column data within a dataframe in which each row represents one patient's data. I have a loop function that takes one patient's 'id' to generate 25 'id'.txt files - one for each patient. I now want to loop through the df, pick up individual data points (e.g. the 'fio2' value for patient with id=6) and append it to that patient's .txt file. 
Here is the problem I need some guidance with: when I run the for loops (I've tried multiple variations) all I get is ALL 25 values for all patients are appended to every individual patient's text file.
The df/data look like this

My basic code that create/write to the text files is:
for i in data['id']:
   filename = str(i) + '.txt'
   f = open(filename, 'a+')
   f.write('{}\n'.format('-----------------------------------------------'))
   f.write(datetime.datetime.now().strftime("%d.%m.%y"))
   f.write('{}\n'.format(''))
   f.write('{}\n'.format('Updated summary of patient data'))
   f.close()

I believe (probably incorrectly) that I need a nested loop. How would I modify this code to do what I need done?

A:

You could try something like this:
import pandas as pd

d = {
    'id':range(10),
    'name': list('abcdefghij')
}
df = pd.DataFrame(d)
print(df.head(2))

def search_id_and_return_field(id,return_field_name):
    return df.loc[df.id==id][return_field_name].values[0]

required_ids = [1,5]

for id in required_ids:
    print(search_id_and_return_field(id=id,return_field_name='name'))
    break

In your code, it would fit in somewhere like so:
for i in required_ids:
    filename = str(i) + '.txt'
    f = open(filename, 'a+')
    f.write('{}\n'.format('-----------------------------------------------'))
    f.write(datetime.datetime.now().strftime("%d.%m.%y"))
    f.write('{}\n'.format(search_id_and_return_field(id=i,return_field_name="fio2"))) # Change your fieldname to be returned here
    f.write('{}\n'.format('Updated summary of patient data'))
    f.close()

