Is there a way to use the elements of a string-list first as strings and then as int?
l = ['A','B','C']
for n in l:
use n as string (do some operations)
convert n to int(element of NG)
use n as int
I tried to Play around with range/len but I didnt come to a solution.
Edit2:
This is what I have:
import pandas as pd
import matplotlib.pyplot as plt
NG = ['A','B','C']
l = [1,2,3,4,5,6]
b = [6,5,4,3,2,1]
for n in NG:
print(n)
dflist = []
df = pd.DataFrame(l)
dflist.append(df)
df2 = pd.DataFrame(b)
dflist.append(df2)
df = pd.concat(dflist, axis = 1)
df.plot()
The Output are 3 figures that look like this:
But I want them to be in one figure:
import pandas as pd
import matplotlib.pyplot as plt
NG = ['A','B','C']
l = [1,2,3,4,5,6]
b = [6,5,4,3,2,1]
for n in NG:
print(n)
dflist = []
df = pd.DataFrame(l)
dflist.append(df)
df2 = pd.DataFrame(b)
dflist.append(df2)
df = pd.concat(dflist, axis = 1)
ax = plt.subplot(6, 2, n + 1)
df.plot(ax = ax)
This code works, but only if the list NG is made out of integers [1,2,3]. But I have it in strings. And I Need them in the Loop.
How to access both the element of list and its index?
That is the real question as I understood mainly from this comment. And it is a pretty common and straightforward piece of code:
NG = ['A', 'B', 'C']
for i in range(len(NG)):
print(i)
print(NG[i])
Here is my 2 cents:
>>> for n in l:
... print ord(n)
... print n
...
65
A
66
B
67
C
To convert back to char
>>> chr(65)
'A'
I think integer mean here is ascii value of character
so you can use again your ascii value to play with characters
my solution is you have to type cast your variables like this ,
and use ord() function to get ascii values
l = ['A','B','C']
for i in range(0,len(l)):
print("string value is ",l[i])
# now for integer values
if type(l[i]) != 'int':
print("ascii value of this char is ",ord(l[i]))
else:
print("already int type go on..")
as because there is no meaning of having a int value of characters , int value of character generally refers as ascii value may be some other formats
Use enumerate to iterate both on the indices and the letters.
NG = ['A','B','C']
for i, n in enumerate(NG, 1):
print(i, n)
Will output:
(1, 'A')
(2, 'B')
(3, 'C')
In your case, because you don't need the letters at all in your loop, you can use the underscore _ to notify coders in your future about what your code do - it uses the len of NG just for the indices.
for i, _ in enumerate(NG, 1):
Related
I want to search a value in a 2d array and get the value of the correspondent "pair"
in this example i want to search for 'd' and get '14'.
I did try with np location with no success and i finished with this crap code, someone else has a smarter solution?
`
import numpy as np
ar=[[11,'a'],[12,'b'],[13,'c'],[14,'d']]
arr = np.array(ar)
x = np.where(arr == 'd')
print(x)
print("x[0]:"+str(x[0]))
print("x[1]:"+str(x[1]))
a = str(x[0]).replace("[", "")
a = a.replace("]", "")
a = int (a)
print(a)
b = str(x[1]).replace("[", "")
b = b.replace("]", "")
b = int (b) -1
print(b)
print(ar[a][b])
#got 14
`
So you want to lookup a key and get a value?
It feels like you need to use dict!
>>> ar=[[11,'a'],[12,'b'],[13,'c'],[14,'d']]
>>> d = dict([(k,v) for v,k in ar])
>>> d
{'a': 11, 'b': 12, 'c': 13, 'd': 14}
>>> d['d']
14
Use a dict, simple and straight forward:
dct = {k:v for v,k in ar}
dct['d']
If you are hell bent on using np.where, then you can use this:
import numpy as np
ar = np.array([[11,'a'],[12,'b'],[13,'c'],[14,'d']])
i = np.where(ar[:,1] == 'd')[0][0]
result = ar[i, 0]
I didn't know about np.where! It's docstring mentions using nonzero directly, so here's a code snippet that uses that to print the rows that match your requirement: note I add another row with 'd' to show it works for the general case where you want multiple rows matching the condition:
ar=[[11,'a'],[12,'b'],[13,'c'],[14,'d'],[15,'e'],[16,'d']]
arr = np.array(ar)
rows = arr[(arr=='d').nonzero()[0], :]
# array([['14', 'd'],
# ['16', 'd']], dtype='<U21')
This works because nonzero (or where) returns a tuple of row/column indexes of the match. So we just use the first entry in the tuple (an array of row indexes) to index the array row-wise and ask Numpy for all columns (:). This makes the code a bit fragile if you move to 3D or higher dimensions, so beware.
This is assuming you really do intend to use Numpy! Dict is better for many reasons.
You are given as input lines of a file containing a list and integer which is associated with a variable.
line = 1,2,3,4;5
How do i go about making an array out of the first 4 elements [1,2,3,4] and assigning the last element 5 to variable K?
I wanted to split it and get this:
arr = [1,2,3,4]
k = 5
text = "1,2,3,4;5"
myList = text.split(";")
k = int(myList[-1])
myList.pop()
arr = myList
n = len(arr)
i = 0
while(i<n):
left = i
right = min(i + k - 1, n - 1)
while (left < right):
arr[left], arr[right] = arr[right], arr[left]
left+= 1;
right-=1
i+= k
for i in range(0, n):
print(arr[i], end ="")
Thank you everyone. I just needed to split the input and change the type from string to integer.
Here's a one line version using the re module:
import re
line = '1,2,3,4;5'
*arr, k = re.split('[,;]', line)
This gives:
print(arr, k)
['1', '2', '3', '4'] 5
If you need the array (Python list) to be integers instead of strings, you can use:
arr = [int(s) for s in arr]
Hi looking at the input you gave 1,2,3,4;5
If this is the input then:
(a,k) = input().split (";") #this will sperate 1,2,3,4 to arr and 5 to k
arr = a.split(",") #it sperate 1234 and makes a list
print(arr,r)
Please tell me if it works
Here is what you can try:
x='1,2,3,4;5'.split(",")
last=int(x[-1].split(";")[1])
x[-1]=x[-1].split(';')[0]
print(x,last)
OR
x='1,2,3,4;5'.split(';')
print(list(x[0].split(',')),int(x[1]))
You could do something like this:
>>> line = '1,2,3,4;5'
>>> arr, k = line.split(';')
>>> arr = arr.split(',')
>>> arr
['1', '2', '3', '4']
>>> k
5
line.split(';') will split the value separated by ; into two lists.
arr.split(',') will then split all the value separated by ,.
I want my code to compute the sum of the values in the numeric column X per value of column Y
reader = csv.reader(f)
csv_l=list(reader)
rows = len(csv_l)-1
columns = len(csv_l[0])
without_header = csv_l[1:]
number_list = [[int(x) if x.isdigit() else x for x in lst] for lst in without_header]
my_dict = {}
for d in number_list:
if d[0] in my_dict.keys():
my_dict[d[0]] += d[3]
else:
my_dict[d[0]] = d[3]
If the value in the input CSV column is an integer, it works perfectly fine but I have found that if the value is a float, isdigit() fails and it returns the result as the floats pieced together as strings instead of an addition.
I used pandas for this and here it works, but I would want it in "pure python".
dataframe = pd.read_csv(filePath)
new_dataframe = dataframe.groupby('Column Y')['Column X'].sum().reset_index(name='Sum of Values')
return(new_dataframe)
Is this close to what you are trying to achieve?
Setting up the data:
import numpy as np
import pandas as pd
df = pd.DataFrame({'X': np.random.choice(list('ABCD'), size=16),
'Y': np.random.random(size=16)})
table = df.values
Grouping by X column without pandas, iteratively filling a dict:
res = {}
for n, v in table:
if n in res.keys():
res[n] += v
else:
res[n] = v
Perhaps something along these lines is what you are looking for?
reader = csv.reader(f)
csv_l=list(reader)
rows = len(csv_l)-1
columns = len(csv_l[0])
without_header = csv_l[1:]
def x_to_num(x):
try:
x = int(x)
except Exception:
pass
return x
number_list = [[x_to_num(x) for x in lst] for lst in without_header]
my_dict = {}
for d in number_list:
if d[0] in my_dict.keys():
my_dict[d[0]] += d[3]
else:
my_dict[d[0]] = d[3]
If x is numeric, then it converts x to an integer, otherwise, it leaves x as is.
how can we use for loop to assign two values from the string like following
string="abcd"
for i in string:
print(i)
this will give i one value from the string
#output
a
b
c
d
how can i take two values like ab and cd. I know we can do this in print but i need to assign two values in "i"
I need output
#output
ab
cd
You could use list-comprehension like the following:
n = 2
s = "abcd"
res = [s[i:i+n] for i in range(0, len(s), n)]
print(res) # ['ab', 'cd']
This is applicable to any nth place.
If its only 2 chars that you are after you can also use regex, but if it for any n its not convenient, an example for n=2 is:
import re
s = "abcd"
res = re.findall('..?',s)
print(res) # ['ab', 'cd']
Try this:
string = "abcd"
for i in range(1,len(string),2):
print(string[i-1]+string[i])
Output:
ab
cd
Explanation
You can modify the range function to start at index 1 and go all the way through len(string) in steps of 2(range(1,len(string),2))
Then inside the loop, since we start index 1, we print string[i-1] and concatenate with string[i]
I have a list of values in a for loop. e.g. myList = [1,5,7,3] which I am using to create a bar chart (using google charts)
I want to label each value with a letter of the alphabet (A-Z) e.g. A = 1, B = 5, C = 7, D = 3
What is the best way to do this running through a for loop
e.g.
for x in myList:
x.label = LETTER OF THE ALPHABET
The list can be any length in size so wont always be just A to D
EDIT
myList is a list of objects not numbers as I have put in example above. Each object will have a title attached to it (could be numbers, text letters etc.), however these titles are quite long so mess things up when displaying them on Google charts. Therefore on the chart I was going to label the chart with letters going A, B, C, ....to the lenth of the myList, then having a key on the chart cross referencing the letters on the chart with the actual titles. The length of myList is more than likely going to be less than 10 so there would be no worries about running of of letters.
Hope this clears things up a little
If you want to go on like ..., Y, Z, AA, AB ,... you can use itertools.product:
import string
import itertools
def product_gen(n):
for r in itertools.count(1):
for i in itertools.product(n, repeat=r):
yield "".join(i)
mylist=list(range(35))
for value, label in zip(mylist, product_gen(string.ascii_uppercase)):
print(value, label)
# value.label = label
Part of output:
23 X
24 Y
25 Z
26 AA
27 AB
28 AC
29 AD
import string
for i, x in enumerate(myList):
x.label = string.uppercase[i]
This will of course fail if len(myList) > 26
import string
myList = [1, 5, 7, 3]
labels = [string.uppercase[x+1] for x in myList]
# ['C', 'G', 'I', 'E']
for i in range(len(myList)):
x.label = chr(i+65)
More on the function here.
charValue = 65
for x in myList:
x.label = chr(charValue)
charValue++
Be careful if your list is longer than 26 characters
First, if myList is a list of integers, then,
for x in myList:
x.label = LETTER OF THE ALPHABET
won't work, since int has no attribute label. You could loop over myList and store the labels in a list (here: pairs):
import string
pairs = []
for i, x in enumerate(myList):
label = string.letters(i) # will work for i < 52 !!
pairs.append( (label, x) )
# pairs is now a list of (label, value) pairs
If you need more than 52 labels, you can use some random string generating function, like this one:
import random
def rstring(length=4):
return ''.join([ random.choice(string.uppercase) for x in range(length) ])
Since I like list comprehensions, I'd do it like this:
[(i, chr(x+65)) for x, i in enumerate([1, 5, 7, 3])]
Which results in:
[(1, 'A'), (5, 'B'), (7, 'C'), (3, 'D')]
import string
for val in zip(myList, string.uppercase):
val[0].label = val[1]
You can also use something like this:
from string import uppercase
res = ((x , uppercase[i%26]*(i//26+1)) for i,x in enumerate(inputList))
Or you can use something like this - note that this is just an idea how to deal with long lists not the solution:
from string import uppercase
res = ((x , uppercase[i%26] + uppercase[i/26]) for i,x in enumerate(inputList))
Are you looking for a dictionary, where each of your values are keyed to a letter of the alphabet? In that case, you can do:
from string import lowercase as letters
values = [1, 23, 3544, 23]
mydict = {}
for (let, val) in zip(letters, values):
mydict[let] = val
<<< mydict == {'a': 1, 'c': 23, 'b': 3544, 'd': 23}
<<< mydict['a'] == 1
You'll have to add additional logic if you need to handle lists longer than the alphabet.