Reading An N-dimensional Complex Array From A Text File To Numpy
I am trying to read a N-dimensional complex array from a text file to numpy. The text file is formatted as shown below (including the square brackets in the text file, in a single
Solution 1:
Here You go:
=^..^=
import numpy as np
import re
# collect raw data
raw_data = []
withopen('data.txt', 'r') as data_file:
for item in data_file.readlines():
raw_data.append(item.strip('\n'))
data_array = np.array([])
for item in raw_data:
# remove brackets
split_data = re.split('\]', item)
for string in split_data:
# clean data
clean_data = re.sub('\[+', '', string)
clean_data = re.sub('i', 'j', clean_data)
# split data
split_data = re.split(' ', clean_data)
split_data = list(filter(None, split_data))
# handle empty listiflen(split_data) == 0:
passelse:
# collect data
data_array = np.hstack((data_array, np.asarray(split_data).astype(np.complex)))
# reshape array
final_array = np.reshape(data_array, (int(data_array.shape[0]/12),4,3))
Output:
[[[-0.26905 +0.956854j -0.96105 +0.319635j -0.306649+0.310259j]
[ 0.27701 -0.943866j -0.946656-0.292134j -0.334658+0.988528j]
[-0.263606-0.340042j -0.958169+0.867559j 0.349991+0.262645j]
[ 0.32736 +0.301014j 0.941918-0.953028j -0.306649+0.310259j]][[-0.9462 -0.932573j 0.968764+0.975044j 0.32826 -0.925997j]
[-0.306461-0.9455j -0.953932+0.892267j -0.929727-0.331934j]
[-0.958728+0.31701j -0.972654+0.309404j -0.985806-0.936901j]
[-0.312184-0.977438j -0.974281-0.350167j -0.305869+0.926815j]][[-0.26905 +0.956854j -0.96105 +0.319635j -0.306649+0.310259j]
[ 0.27701 -0.943866j -0.946656-0.292134j -0.334658+0.988528j]
[-0.263606-0.340042j -0.958169+0.867559j 0.349991+0.262645j]
[ 0.32736 +0.301014j 0.941918-0.953028j -0.306649+0.310259j]][[-0.9462 -0.932573j 0.968764+0.975044j 0.32826 -0.925997j]
[-0.306461-0.9455j -0.953932+0.892267j -0.929727-0.331934j]
[-0.958728+0.31701j -0.972654+0.309404j -0.985806-0.936901j]
[-0.312184-0.977438j -0.974281-0.350167j -0.305869+0.926815j]]]
Solution 2:
as it seems your file is not in a "pythonic" list ( no comma between object).
I assume the following:
- you can not change your input, you get it from 3rd party source)
- the file is not a csv. ( no delimiter between rows)
as a result :
- try to convert the strings to python string, after each "[]" add "," -->
[[1+2j, 3+4j], [1+2j, 3+4j]]
- between each number add "," and change from "i" to "j" [-0.26905+0.956854j, -0.96105+0.319635j, -0.306649+0.310259j]
- python complex number is with the letter j
1+2j
- then save it as csv.
- open with pandas, read scv look at the link : python pandas complex number
Post a Comment for "Reading An N-dimensional Complex Array From A Text File To Numpy"