гиви
гиви

Reputation: 69

Python - How to rearrange datas in array?

I work with this kind of array, they are straight from a spectrometer (wavelength, intensity) and I had to treat them with python.

280.0,1.0
280.4031007751938,1.0
280.8062015503876,1.0
281.2093023255814,1.0
281.61240310077517,1.0
282.015503875969,1.0
282.4186046511628,1.0
282.8217054263566,1.0
283.2248062015504,1.0
283.6279069767442,1.0
284.031007751938,1.0
284.4341085271318,1.0
284.83720930232556,1.0
285.2403100775194,1.0
285.6434108527132,1.0
286.04651162790697,1.0
286.4496124031008,1.0
286.85271317829455,1.0
287.25581395348837,1.0
287.6589147286822,1.0
288.06201550387595,1.0
288.4651162790698,1.0
288.86821705426354,1.0
289.27131782945736,1.0
289.6744186046512,1.0909090909090908
290.07751937984494,1.1818181818181819

My problem is that the function which uses these datas in my python program wants an array where wavelength data is separated from intensity by a :. This form 280: 0.1,. So I am looking for a way to replace the , by a : and put a , to separate from other datas. I do not know how to do that, is NumPy able to do that ?

I also look for a way to extract some specific values (with a definable step) from the starting data array.

I also want to remove all decimals for the wavelength as you can see in the below expected example but I think I will be able to deal with this part.

The idea is to have, at the end, such a array :

data_sample = {380: 11.0,
           385: 11.0,
           390: 11.0,
           395: 11.545454545454545,
           400: 12.363636363636363,
           405: 13.454545454545455,
           410: 14.0,
           415: 14.181818181818182,
           420: 15.363636363636363,}

I hope I succeed to well describe what I am trying to do and you can help me or guide me towards answers.

Thank you very much :)

Upvotes: 0

Views: 55

Answers (1)

Martin Tovmassian
Martin Tovmassian

Reputation: 1438

As I understand the colour.SpectralDistribution method you need to pass a dictionary as argument where wavelength is the key and intensity the value.

Basically, for each line you read in your input file you have to:

  • split it based on the comma separator to retrieve the wavelength at the leftend and the intensity at the rightend
  • convert values from string to float + round the wavelength value
  • push the wavelength and intensity as key/value pair into a dictionary.

You can achieve this goal like so:

with open("raw_data.txt", "r") as raw_data_file:
  lines = [line.rstrip("\n").split(",") for line in raw_data_file]
  
spectral_distribution_input = {
  round(float(wavelength)): float(intensity) for (wavelength, intensity) in lines
}

Upvotes: 1

Related Questions