I would to run a loop which retrieve data from a function (not coded in the loop) for each base_currency. The code run without error but it displays 5 times (number of base_currency) the first items in the list instead of looping one after the other (the x in the function is not working properly).
The code:
base_currency = ['BTC','ABX','ADH','ALX','1WO']
length = len(base_currency)
d_volu = []
i = 0
while i < length:
for x in base_currency:
volu = daily_volume_historical(x, 'JPY', exchange='CCCAGG').set_index('timestamp').volume
d_volu.append(volu)
i += 1
d_volu = pd.concat(d_volu, axis=1)
print(d_volu)
Thank you
You're looping over base_currency twice as mentioned by #Grismar. You can avoid confusion by using list comprehension like this.
base_currency = ['BTC','ABX','ADH','ALX','1WO']
d_volu = [daily_volume_historical(x, 'JPY', exchange='CCCAGG').set_index('timestamp').volume
for x in base_currency]
Related
If I have a dictionary like this, filled with similar lists, how can I apply a while loo tp extract a list that prints that second element:
racoona_valence={}
racoona_valence={"rs13283416": ["7:87345874365-839479328749+","BOBB7"],\}
I need to print the part that says "BOBB7" for 2nd element of the lists in a larger dictionary. There are ten key-value pairs in it, so I am starting it like so, but unsure what to do because all the examples I can find don't relate to my problem:
n=10
gene_list = []
while n>0:
Any help greatly appreciated.
Well, there's a bunch of ways to do it depending on how well-structured your data is.
racoona_valence={"rs13283416": ["7:87345874365-839479328749+","BOBB7"], "rs13283414": ["7:87345874365-839479328749+","BOBB4"]}
output = []
for key in racoona_valence.keys():
output.append(racoona_valence[key][1])
print(output)
other_output = []
for key, value in racoona_valence.items():
other_output.append(value[1])
print(other_output)
list_comprehension = [value[1] for value in racoona_valence.values()]
print(list_comprehension)
n = len(racoona_valence.values())-1
counter = 0
gene_list = []
while counter<=n:
gene_list.append(list(racoona_valence.values())[n][1])
counter += 1
print(gene_list)
Here is a list comprehension that does what you want:
second_element = [x[1] for x in racoona_valence.values()]
Here is a for loop that does what you want:
second_element = []
for value in racoona_valence.values():
second_element.append(value[1])
Here is a while loop that does what you want:
# don't use a while loop to loop over iterables, it's a bad idea
i = 0
second_element = []
dict_values = list(racoona_valence.values())
while i < len(dict_values):
second_element.append(dict_values[i][1])
i += 1
Regardless of which approach you use, you can see the results by doing the following:
for item in second_element:
print(item)
For the example that you gave, this is the output:
BOBB7
I am trying to use a list that I created in a previous function. The list is a set of times (each second is a point) and I need to add points every 1/20th of a second. The list of times was created in a previous function, but when I try to call back the list to np.linspace it, I get a typeerror code saying the global name list1 was not defined.
I've already tried renaming the list to something different like time = [], but this does not help. I've also defined the empty list in the function and outside of the function.
def time_finder():
v = 0
u = 0
list1 = []
while v < 286:
v = v + 1
u = u + 1
z = mce_data[0]
y = [a for b in z for a in b]
x = (y)[u]
w = np.array(x)[0]
x.tolist()
list1.append(w)
return (list1)
#print(list1)
time_finder()
#adds 1/20th second marks
def twentieth_second():
u = 0
while u < 286:
v = 1
timea = list1[u]
timeb = list1[v]
np.linspace(timea, timeb, parts+19)
u = u + 1
v = v + 1
print list1
twentieth_second()
The error that I get is NameError: global name 'list1' is not defined. This error changes depending on the troubleshooting that I do. Sometimes I get a call back error and other times I get an index is out of range error. I'm expecting to get a new list printed with the 1/20 second intervals included.
you need to assign the results of the first function to a variable:
list1 = time_finder()
It may even help to move that line into twentieth_second
Also your return in the time_finder is wrong. Remove the () around list1
#return (list1)
return list1
cust_id = semi_final_df['0_x'].tolist()
date = semi_final_df[1].tolist()
total_amount = semi_final_df[0].tolist()
prod_num = semi_final_df['0_y'].tolist()
prod_deduped = []
quant_cleaned = []
product_net_amount = []
cust_id_final = []
date_final = []
for row in total_amount:
quant_cleaned.append(float(row))
for unique_prodz in prod_num:
if unique_prodz not in prod_deduped:
prod_deduped.append(unique_prodz)
for unique_product in prod_deduped:
indices = [i for i, x in enumerate(prod_num) if x == unique_product]
product_total = 0
for index in indices:
product_total += quant_cleaned[index]
product_net_amount.append(product_total)
first_index = prod_num.index(unique_product)
cust_id_final.append(cust_id[first_index])
date_final.append(date[first_index])
Above code calculates sum amount by one condition in order to sum the total on an invoice.
The data had multiple lines but shared the same invoice/product number.
Problem:
I need to modify the below code so that I can sum by unique product and unique date.
I have given it a go but I am getting a value error -
saying x, y is not in a list
As per my understanding the issue lies in the fact that I am zipping two de-duped lists together of different lengths and then I am attempting to loop through the result inline.
This line causes the error
for i,[x, y] in enumerate(zipped_list):
Any help would be sincerely appreciated. Here is the second batch of code with comments.
from itertools import zip_longest
#I have not included the code for the three lists below but you can assume they are populated as these are the lists that I will be #working off of. They are of the same length.
prod_numbers = []
datesz = []
converted_quant = []
#Code to dedupe date and product which will end up being different lengths. These two lists are populated by the two for loops below
prod_deduped = []
dates_deduped = []
for unique_prodz in prod_numbers:
if unique_prodz not in prod_deduped:
prod_deduped.append(unique_prodz)
for unique_date in datesz:
if unique_date not in dates_deduped:
dates_deduped.append(unique_date)
#Now for the fun part. Time to sum by date and product. The three lists below are empty until we run the code
converted_net_amount = []
prod_id_final = []
date_final = []
#I zipped the list together using itertools which I imported at the top
for unique_product, unique_date in zip_longest(prod_deduped, dates_deduped, fillvalue = ''):
indices = []
zipped_object = zip(prod_numbers, datesz)
zipped_list = list(zipped_object)
for i,[x, y] in enumerate(zipped_list):
if x == unique_product and y == unique_date:
indices.append(i)
converted_total = 0
for index in indices:
converted_total += converted_quant[index]
converted_net_amount.append[converted_total]
first_index = zipped_list.index([unique_product, unique_date])
prod_id_final.append(prod_numbers[first_index])
date_final.append(datesz[first_index])
from collections import defaultdict
summed_dictionary = defaultdict(int)
for x, y, z in list:
summed_dictionary[(x,y)] += z
Using defaultdict should solve your problem and is a lot easier on the eyes than all your code above. I saw this on reddit this morning and figured you crossposted. Credit to the guy from reddit on /r/learnpython
I'm having some troubles trying to use four lists with the zip function.
In particular, I'm getting the following error at line 36:
TypeError: zip argument #3 must support iteration
I've already read that it happens with not iterable objects, but I'm using it on two lists! And if I try use the zip only on the first 2 lists it works perfectly: I have problems only with the last two.
Someone has ideas on how to solve that? Many thanks!
import numpy
#setting initial values
R = 330
C = 0.1
f_T = 1/(2*numpy.pi*R*C)
w_T = 2*numpy.pi*f_T
n = 10
T = 1
w = (2*numpy.pi)/T
t = numpy.linspace(-2, 2, 100)
#making the lists c_k, w_k, a_k, phi_k
c_karray = []
w_karray = []
A_karray = []
phi_karray = []
#populating the lists
for k in range(1, n, 2):
c_k = 2/(k*numpy.pi)
w_k = k*w
A_k = 1/(numpy.sqrt(1+(w_k)**2))
phi_k = numpy.arctan(-w_k)
c_karray.append(c_k)
w_karray.append(w_k)
A_karray.append(A_k)
phi_karray.append(phi_k)
#making the function w(t)
w = []
#doing the sum for each t and populate w(t)
for i in t:
w_i = ([(A_k*c_k*numpy.sin(w_k*i+phi_k)) for c_k, w_k, A_k, phi_k in zip(c_karray, w_karray, A_k, phi_k)])
w.append(sum(w_i)
Probably you mistyped the last 2 elements in zip. They should be A_karray and phi_karray, because phi_k and A_k are single values.
My result for w is:
[-0.11741034896740517,
-0.099189027720991918,
-0.073206290274556718,
...
-0.089754003567358978,
-0.10828235682188027,
-0.1174103489674052]
HTH,
Germán.
I believe you want zip(c_karray, w_karray, A_karray, phi_karray). Additionally, you should produce this once, not each iteration of the for the loop.
Furthermore, you are not really making use of numpy. Try this instead of your loops.
d = numpy.arange(1, n, 2)
c_karray = 2/(d*numpy.pi)
w_karray = d*w
A_karray = 1/(numpy.sqrt(1+(w_karray)**2))
phi_karray = numpy.arctan(-w_karray)
w = (A_karray*c_karray*numpy.sin(w_karray*t[:,None]+phi_karray)).sum(axis=-1)
If you have a list of 100 values, which you want to subset into 3 in the ratio 2:1:1, what's the easiest way to do this in Python?
My current solution is to take a sample of the indices for each subset then remove these values from the original list, i.e.
my_list = [....]
num_A = 50
subset_A = []
num_B = 25
subset_B = []
num_C = 25
subset_C = []
a_indices = random.sample(xrange(len(my_list)), num_A)
for i in sorted(a_indices, reverse=True): # Otherwise can get index out of range
subset_A.append(my_list.pop(i))
b_indices = random.sample(xrange(len(my_list)), num_B)
for i in sorted(b_indices, reverse=True): # Otherwise can get index out of range
subset_B.append(my_list.pop(i))
subset_C = my_list[:]
assert len(subset_C) == num_C
However I'm sure there's a much more elegant solution than this.
There's a much easier way. You can just shuffle the array and take parts.
xs = [...]
random.shuffle(xs)
print(xs[:50], xs[50:75], xs[75:])