0

I am currently working to process some data that are imported to Python as a dataframe that has 10000 rows and 20 columns. The columns store sample names and chemical element. The daaaframe is currently indexed by both sample name and time, appearing as so: [1]: https://i.sstatic.net/7knqD.png .

From this dataframe, I want to create individual arrays for each individual sample, of which there are around 25, with a loop. I have generated an index and array of the sample names, which yields an array that appears as so

samplename = fuegodataframe.index.levels[0] samplearray = samplename.to_numpy()

array(['AC4-EUH41', 'AC4-EUH79N', 'AC4-EUH79S', 'AC4-EUH80', 'AC4-EUH81', 'AC4-EUH81b', 'AC4-EUH82N', 'AC4-EUH82W', 'AC4-EUH84', 'AC4-EUH85N', 'AC4_EUH48', 'AC4_EUH48b', 'AC4_EUH54N', 'AC4_EUH54S', 'AC4_EUH60', 'AC4_EUH72', 'AC4_EUH73', 'AC4_EUH73W', 'AC4_EUH78', 'AC4_EUH79E', 'AC4_EUH79W', 'AC4_EUH88', 'AC4_EUH89', 'bhvo-1', 'bhvo-2', 'bir-1', 'bir-2', 'gor132-1', 'gor132-2', 'gor132-3', 'sc ol-1', 'sc ol-2'], dtype=object)

I have also created a dictionary with keys of each of these variable names. I am now wondering how I would use this dictionary to generate individual variables for each of these samples that capture all the rows in which a sample is found.

I have tried something along these lines:

for ii in sampledictionary.keys():
     if ii == sampledictionary[ii]: 
        sampledictionary[ii] = fuegodataframe.loc[sampledictionary[ii]]

but this fails. How would I actually go about doing something like this? Is this possible?

1 Answer 1

1

I think you're asking how to generate variables dynamically rather than assign your output to a key in your dictionary.

In Python there is a globals function globals() that will output all the variable names defined in the document.

You can assign new variables dynamically to this dictionary

globals()[f'variablename_{ii}'] = fuegodataframe.loc[sampledictionary[ii]]

etc.

if ii was 0 then variablename_0 would be available with the assigned value.

In general this is not considered good practice but it is required sometimes.

Sign up to request clarification or add additional context in comments.

2 Comments

clever and sometimes useful
globals() is a dictionary so it can be added to: >>> cheat Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'cheat' is not defined >>> type(globals())<class 'dict'> >>> globals()['cheat'] = 123 >>> cheat 123 p.s likewise for locals()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.