Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
Improve this question
I have the following matrix (or 2D list):
matrix = [['0','0'],
['2','3'],
['1','9'],
['7','11'],
['1','2'],
['7','23'],
['0','0'],
['6','8'],
['3','1'],
['8','1'],
['4','3'],
['0','0'],
['63','9'],
['31','10'],
['82','11'],
['41','31']]
I would like to split it into multiple matrices based on the value in the row. The zeros will determine the location of the split:
matrix1 = [['0','0'],
['2','3'],
['1','9'],
['7','11'],
['1','2'],
['7','23']]
matrix2 = [['0','0'],
['6','8'],
['3','1'],
['8','1'],
['4','3']]
matrix3 = [['0','0'],
['63','9'],
['31','10'],
['82','11'],
['41','31']]
Then I need to write them to a CSV file (adjacent to each other) like this:
import csv
from itertools import zip_longest
matrix = [['0','0'],
['2','3'],
['1','9'],
['7','11'],
['1','2'],
['7','23'],
['0','0'],
['6','8'],
['3','1'],
['8','1'],
['4','3'],
['0','0'],
['63','9'],
['31','10'],
['82','11'],
['41','31']]
zero_pos = [i for i,element in enumerate(matrix) if element == ['0', '0']]
num_mats = len(zero_pos)
matrices = [matrix[zero_pos[i]:zero_pos[i+1]] if i+1<num_mats else matrix[zero_pos[i]:] for i in range(num_mats)]
with open('temp_output.csv', 'w', newline = '') as csv_file:
writer = csv.writer(csv_file, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row in zip_longest(*matrices):
writer.writerow([element for matrix in row if matrix is not None for element in matrix])
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
Improve this question
This is my code ,it is extremely big for something this simple ,how should i make it better?
import numpy
charStats = {'health': 50 ,'damage': 10.1}
charList = []
numbyO = -1
for x in charStats:
numbyO += 1
charList.append(charStats[x])
print(int(numpy.mean(charList)))
You don't need to create charList; just use dict.values():
from statistics import mean
char_stats = {'health': 50 ,'damage': 10.1}
print(int(mean(char_stats.values())))
You can creat a class object and reuse this code,,,
import numpy
class GetMean:
"""make a class object that takes a dict. argument"""
def __init__(self, dict_argument):
#creat dict. attribute
self.dict_argument = dict_argument
#creat list attribute
self.char_list = []
#creat numby_0 attribute
self.numby_0 = -1
def return_mean(self):
#method that returns mean
for x in self.dict_argument:
self.numby_0 +=1
self.char_list.append(self.dict_argument[x])
mean = (int(numpy.mean(self.char_list)))
return mean
charStats = {'health': 50 ,'damage': 10.1}
get_mean = GetMean(charStats)
#instanting GetMean object
mean = get_mean.return_mean()
#using return mean method
print(mean) #showing result
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
How can I split a 'time' value into two 'day' 'time' lists?
See attached image:
If you have it as datetimeobject:
datos['day'] = dados['time'].dt.date
datos['time'] = dados['time'].dt.time
If you have it as string object:
datos['day'] = dados['time'].str[:11]
datos['time'] = dados['time'].str[11:]
Or
data[['day', 'time']] = data['time'].str.split(' ').apply(pd.Series)
data[['day', 'time']] = data['time'].str.split(' ', expand=True)
Or using regex
data[['day', 'time']] = data['time'].str.extract('(.*) (.*)')
To convert it to string:
datos['time'] = dados['time'].astype(str)
It is better then converting to normal list [str(x) ...]
To convert it to datetime
datos['time'] = pd.to_datetime(dados['time'])
It may use options - ie. yearfirst=True, dayfirst=True, format="%Y-%m-%d %H:%I:%S"
I use this for resolve the problem, is there any cleaner way?
dia = [str(x) for x in dados.time]
hora = [str(x) for x in dados.time]
for x in range(len(dia)):
dia [x]=dia [x][0:11]
hora[x]=hora[x][11:20]
dados.insert(0, 'dia', dia)
dados.insert(1, 'hora', hora)
dados.drop(columns='time',inplace=True)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
I have a list Let's say
m = [["'ghvghvgh hgdghdh', 'hxjhsdhb.com - Error 404:validation', 'jhhscbhjbcsd', 'hghs'"],["'ghvh', 'hxjhsdhb', 'jhhcsd', 'hs'"]]
and I want my output something like this (removing the double quotes).
m = [['ghvghvgh hgdghdh', 'hxjhsdhb.com - Error 404:validation', 'jhhscbhjbcsd', 'hghs'],['ghvh', 'hxjhsdhb', 'jhhcsd', 'hs']] ```
m[0][0].replace('"', '') # I have tried this
To normalise the data, you need to replace the single quotes and not the double-ones the trim away extra spaces.
lst = [
i[0].replace("'", '').strip().split(', ')
for i in m
]
import re
a=re.compile('[a-zA-Z]+')
m = [["'ghvghvgh', 'hxjhsdhb', 'jhhscbhjbcsd', 'hghs' "],[" 'ghvh', 'hxjhsdhb', 'jhhcsd', 'hs'"]]
res= [[a.findall(i) for i in j][0] for j in m]
print(res)
output
[['ghvghvgh', 'hxjhsdhb', 'jhhscbhjbcsd', 'hghs'], ['ghvh', 'hxjhsdhb', 'jhhcsd', 'hs']]
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm a new python user. I try to write a script to deal with multiple text files all of them the same name and indexed like
sample1_freq780Hz_accRate600Hz_V3Volt_1_.txt
sample1_freq780Hz_accRate600Hz_V3Volt_2_.txt
sample1_freq780Hz_accRate600Hz_V3Volt_3_.txt
I used this code:
def get_numbers_from_filename(filename):
result = re.search(r'\d+', filename).group(0)
return result for filename in os.listdir('input/'):
print(get_numbers_from_filename(filename))
but it didn't give me the wanted results
I need a code to get the numbers as follow:
freq: 780 Hz
accRate: 600 Hz
V: 3 Volt
and how to deal and use these numbers as parameters inside the full script?
You can use regex:
import re
import os
new_s = [dict(zip(['freq', 'accRate', 'V'], ['{} {}'.format(c, a) for a, c in zip(['Hz', 'Hz', 'Volt'], re.findall('(?<=freq)\d+|(?<=accRate)\d+|(?<=V)\d+', i))])) for i in os.listdir('input/')]
print(new_s[0])
Output:
{'freq': '780 Hz', 'accRate': '600 Hz', 'V': '3 Volt'}
To access the values in the list, iterate over new_s:
values = [new_s[0][i] for i in ['freq', 'accRate', 'V']]
Output:
['780 Hz', '600 Hz', '3 Volt']
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Following is my code:
Here is the main function
trainingSet=[]
testSet=[]
validationSet=[]
loadDataset('iris.data.txt', trainingSet, testSet,validationSet)
And this is the loadDataset function
def loadDataset(filename, trainingSet=[] ,testSet=[],validationSet=[]):
with open(filename, 'rb') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for x in range(len(dataset)-1):
for y in range(4):
dataset[x][y] = float(dataset[x][y])
random.shuffle(dataset)
trainingSet .append(dataset[:106])
testSet.append(dataset[106:128])
validationSet.append(dataset[128:150])
"loadDataset gets wine data set csv and converts it into a list of floats. Then it splits the data."
I am trying to split my data into 70-15-15. But when I print the lengths of each list it gives 1.
Simply using .extend instead of .append should solve your issue. .append adds the slice dataset[xxx] as a single element to the list. .extend, on the other hand, adds all the elements in dataset[xxx] to the list.
However, if you only call loadDataSet once, as in your example, there is no need to initialize empty datasets, and you can return the ranges directly.
main function:
trainingSet, testSet, validationSet = loadDataset('iris.data.txt')
loadDataset function:
def loadDataset(filename):
with open(filename, 'rb') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for x in range(len(dataset)-1):
for y in range(4):
dataset[x][y] = float(dataset[x][y])
random.shuffle(dataset)
trainingSet = dataset[:106]
testSet = dataset[106:128]
validationSet = dataset[128:150]
return trainingSet, testSet, validationSet