create list of data time from an array - arrays

I have a weird format of date time information which is saved as a separate string. Such as,
print(time)
print(time[0])
print(type(time[0]))
print(type(time[0][0]))
[['2' '0' '2' ... '3' '2' '3']
['2' '0' '2' ... '4' '2' '3']
['2' '0' '2' ... '5' '2' '4']
...
['2' '0' '2' ... '5' '2' '7']
['2' '0' '2' ... '6' '2' '6']
['2' '0' '2' ... '7' '2' '0']]
['2' '0' '2' '2' '0' '5' '2' '1' '0' '7' '1' '3' '2' '3']
<class 'numpy.ma.core.MaskedArray'>
<class 'numpy.str_'>
The goal is to convert each row of the array into a proper DateTime format.
The outcome can be both list or an array.
For example,
['2' '0' '2' '2' '0' '5' '2' '1' '0' '7' '1' '3' '2' '3']
into
DateTime format 20220521-07:13:23
As the original data has multiple rows, I need to loop through the array.

suppose your list is:
l = ['2','0','2','2','0','5','2','1','0','7','1','3','2','3']
you can use:
time = [l[8+2*i]+l[9+2*i] for i in range(3)]
date = ''.join(l[:8]) + '- ' + ':'.join(time)
print(date)
>>> 20220521- 07:13:23

Related

character case on a Loop

hope someone can help please. I was able to get the code but unable to display the characters similar to the input. I capitalized the input for comparison but output should be similar to the input. See image pls. Thanks.
morse_code_dict = {
'A' : '.-',
'B' : '-...',
'C' : '-.-.',
'D' : '-..',
'E' : '.',
'F' : '..-.',
'G' : '--.',
'H' : '....',
'I' : '..',
'J' : '.---',
'K' : '-.-',
'L' : '.-..',
'M' : '--',
'N' : '-.',
'O' : '---',
'P' : '.--.',
'Q' : '--.-',
'R' : '.-.',
'S' : '...',
'T' : '-',
'U' : '..-',
'V' : '...-',
'W' : '.--',
'X' : '-..-',
'Y' : '-.--',
'Z' : '--..',
'0' : '-----',
'1' : '.----',
'2' : '..---',
'3' : '...--',
'4' : '....-',
'5' : '.....',
'6' : '-....',
'7' : '--...',
'8' : '---..',
'9' : '----.',
'.' : '.-.-.-',
',' : '--..--'
}
text = input("Please enter the phrase to send: ")
text2 = ' '.join(text.split()).upper()
for character in text2:
if character in morse_code_dict:
print(f"{character} in morse is {morse_code_dict[character]}")
elif character == ' ':
print("Gap")
else:`enter code here`
print(f"{character} is not available in morse.")
correct output
incorrect output I'm getting
Don't convert the string to uppercase before iterating over it, you can use .upper inside the loop. For example:
text = input("Please enter the phrase to send: ")
morse_code_dict[" "] = "Gap"
for ch in " ".join(text.split()):
if ch.upper() in morse_code_dict:
print(f"{ch} in morse is {morse_code_dict[ch.upper()]}")
else:
print(f"{ch} is not available in morse.")
Prints:
T in morse is -
h in morse is ....
e in morse is .
in morse is Gap
l in morse is .-..
a in morse is .-
s in morse is ...
t in morse is -
in morse is Gap
c in morse is -.-.
h in morse is ....
a in morse is .-
r in morse is .-.
a in morse is .-
c in morse is -.-.
t in morse is -
e in morse is .
r in morse is .-.
in morse is Gap
i in morse is ..
s in morse is ...
in morse is Gap
n in morse is -.
o in morse is ---
t in morse is -
in morse is Gap
p in morse is .--.
r in morse is .-.
e in morse is .
s in morse is ...
e in morse is .
n in morse is -.
t in morse is -
! is not available in morse.

Iterate over an array and fill empty adjacent spots in array

I have created an multi dimensional array of empty strings with some row/columns being filled with a letter. Goal is to to fill the adjacent empty slots where the letters are found with that letter. I have most of array filling but I also want to count how many times loops occur to fill array.
This is in python 3 using numpy module only.
It keeps going out of range of index or I get infinite loops.
import numpy as np
letter_spots=[[3,0],[3,4],[1,3]]
A_array= np.zeros([5,5],str)
for lists in letter_spots:
A_array[lists[0]][lists[1]]='A'
for row in range(A_array.shape[0]):
for column in range(A_array.shape[1]):
if A_array[row][column]=='A':
if column+1 < A_array.shape[0]:
if A_array[row][column+1]=='':
A_array[row][column+1]='A'
if column>0:
if A_array[row][column - 1] == '':
A_array[row][column - 1] = 'A'
if row + 1 < A_array.shape[0]:
if A_array[row + 1][column] == '':
A_array[row + 1][column] = 'A'
if row > 0:
if A_array[row - 1][column] == '':
A_array[row - 1][column] = 'A'
Start array:
[['' '' '' '' '']
['' '' '' 'A' '']
['' '' '' '' '']
['A' '' '' '' 'A']
['' '' '' '' '']]
Current End Array:
[['' '' '' 'A' 'A']
['' '' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']]
Expected End Array:
[['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']
['A' 'A' 'A' 'A' 'A']]
You could just use where
import numpy as np
array1 = np.array([2, 2, 2, 0, 2, 0, 2])
print np.where(array1==0, 1, array1)

Count elements in an array

I have an array that contains string elements:
farm = np.array(garden)
leads to this:
[['F' 'F' 'W' 'W']
['F' '_' '_' 'W']
['G' '_' '_' 'J']
['G' 'G' 'J' 'J']]
I want to count how many times lets say 'F' appears, is there a simple way to do this? This is a small version of the bigger array that I will be working on
EDIT:
Lists have a count method. So your new and improved pythonic code is
D= sum([i.count("F") for i in listX])
Well you can make a function, that
Checks if the parameter passed to it is in the array. You can even use list comprehensions. For example
F = sum([sum([1 for i in j if i=="f"]) for j in listX])
Michael's solution is the most "pythonic", but I wanted to offer an alternative solution using simpler constructs, in case you're just learning:
lst = []
lst.append(['F', 'F', 'W', 'W'])
lst.append(['F', '_', '_', 'W'])
lst.append(['G', '_', '_', 'J'])
lst.append(['G', 'G', 'J', 'J'])
numFs = 0
# Look at each sublist
for sublist in lst:
# Look at each element within the sublist
for s in sublist:
# If the element is an 'F', add 1 to the number of Fs
if s == 'F':
numFs += 1
print(numFs)
You could also try to reduce and join the elements of the arrays into a string and then count, like so:
from functools import reduce
a = [['F' 'F' 'W' 'W'], ['F' '_' '_' 'W'], ['G' '_' '_' 'J'], ['G' 'G' 'J' 'J']]
c = ''.join(reduce(list.__add__, a)).count('F')
print(c)
When executed, this code prints:
3

Find row Index of strings in cell Array (Matlab)

If I have a cell array C:
C = {'name' 'hh' '23' [] []
'last' 'bb' '12' '8' 'hello'
'In' 'kk' '12' '2131' []
'name' 'kk' '23' [] []
'name' 'cv' '22' [] []
'name' 'ph' '23' [] [] } ;
How can I get the row index of all the rows that have 'name' in the first column and '23' in the third column?
indexresult = [1,4,6]
The simplest way to do this (all-versions compatible) would be to just use strcmp, which can accept cell arrays and does a "string compare".
One liner
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23'));
% indexresult = [1; 4; 6];
Explanation
% Get logical array of rows where first column is 'name'
logicalname = strcmp(C(:,1), 'name');
% Get logical array of rows where third column is '23'
logical23 = strcmp(C(:,3), '23');
% Get logical array where both of the above are true, using and (&)
logicalname23 = strcmp(C(:,1), 'name') & strcmp(C(:,3), '23');
% Get indices from logical array using find
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23'));
% If you wanted a row vector instead of column vector, just transpose too
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23')).';
If you want to be case insensitive (matching 'name', 'NAME', 'Name', ...) then use strcmpi instead of strcmp.
YOu can use strfind to get the indices which has string name and then use logical indices to get 23 out of the obtained indices.
C = {'name' 'hh' '23' [] []
'last' 'bb' '12' '8' 'hello'
'In' 'kk' '12' '2131' []
'name' 'kk' '23' [] []
'name' 'cv' '22' [] []
'name' 'ph' '23' [] [] } ;
% find indices of name
idx = strfind(C(:,1), 'name');
idx = find(not(cellfun('isempty', idx)));
% pick 23 from 3rc column
iwant =idx((str2double(C(idx,3))==23))

How do I make each sentence into a nested list?

I'm working with a text file that looks like this; (The words are in Swedish)
['1', 'Denna', '_', 'DET', 'DT', 'UTR|SIN|DEF', '2', 'DT', '_', '_\n']
['2', 'predestination', '_', 'NOUN', 'NN', 'UTR|SIN|IND|NOM', '7', 'SS', '_', '_\n']
['3', 'till', '_', 'ADP', 'PP', '_', '2', 'ET', '_', '_\n']
['4', 'en', '_', 'DET', 'DT', 'UTR|SIN|IND', '6', 'DT', '_', '_\n']
.....
There are about 500 sentences of various lenghts; each line describes one word. The first list element gives the word's position in the sentence.
I need my program to make a nested list from the entries for each sentence (one sub-list for each sentence). Every new sentence starts with position '1', and they are separated by empty lines. At the moment all my lines are in one list.
I would like to do something like:
l = []
for line in list:
if line[0] == '1':
l.append(line)
... then append every line that follows until it reaches '1' again, where I start with a new sub-list.
Some ides on how to do it? How could I make this recursive?
This is not a naturally recursive process; it's iterative. A simple loop will do the job.
alla = []
forst = True
for line in list:
if line[1] == '1':
# ny mening
if not forst:
alla.append(mening)
forst = False
mening = []
mening.append(line)
Since the trigger for each append is the start of the sentence, you still have one sentence left to add. I'll leave that part for you to do. :-)

Resources