could you help me with this problem? damned for! :p
def exchange(x):
r = requests.get(URL1 + x + URL2)
js = r.json()
df = pd.DataFrame.from_dict(js, orient="index").transpose()
return df
if capture data with next code, after individual append() i have expected answer:
c = exchange("tiendacrypto")
d = exchange("belo")
c.append(d)
but, i don't find the error in the for:
a = []
for i in exchanges:
print(exchange(i))
a = exchange(i)
a.append(a)
The issue here is the reassignment of the a value on line 2 in the for loop.
You need to use a different variable name.
π = []
πππ π ππ ππ‘πππππππ:
πππππ(ππ‘ππππππ(π))
x = ππ‘ππππππ(π)
π.ππππππ(x)
Notice how we dont now change a in each loop.
You're using a twice.
π = []
πππ π ππ ππ‘πππππππ:
πππππ(ππ‘ππππππ(π))
π = ππ‘ππππππ(π) # Here is overwritten!
π.ππππππ(π)#
results = []
πππ π ππ ππ‘πππππππ:
df = ππ‘ππππππ(π)
πππππ(ππ‘ππππππ(df))
results.ππππππ(df)
Related
From a script, I am getting data like that is given below.
Neha, 30,A
Monika ,22,B
Anni,33,C
I want to convert this data in a given way that is given below.
[{'name':Neha,'age':30,'grade':A},{'name':Monika,'age':22,'grade':B},{'name':Anni,'age':33,'grade':c}]
Can anyone please help me to get the data in this way any suggestion . Thanks in advance
This is your solution
s = """Neha,30,A
Monika,22,B
Anni,33,C"""
# print(s.split('\n'))
l = []
s = s.split('\n')
for i in s:
# print(i)
temp = i.split(',')
# print(temp)
d = {}
d['name'] = temp[0]
d['age'] = temp[1]
d['grade'] = temp[2]
l.append(d)
print(l)
**
def reading_file(rf):
f = open(rf,'r')
print('Rentable Houses Δ°nformation:')
for line in f.readlines():
datas = line.split(',')
c = datas[1]
a = datas[2]
r = datas[3]
hoa = datas[9]
ra = datas[10]
pt = datas[11]
fi = datas[12]
house_info = np.array((c,a,r,hoa,ra,pt,fi))
print(*house_info,sep=',')
f.close()
**
I try to define a function that reads a file then assings all datas to an array. However, I cannot find the use of return. Because of not using return, this function also prints 'None'. Therefore my program do not work effectively. How can I solve this help me?
Solution
You could use numpy.genfromtxt() to first load-in the data as an array and then select only the columns you need by specifying column_indices.
import numpy as np
column_indices = [1,2,3,9,10,11,12]
# fname is the reading-filename.
a = np.genfromtxt(fname, delimiter=',')[:,column_indices]
However, if you just want to return the result from your custom-defined function, you need to add a return statement as follows:
def reading_file(rf):
# define an empty list
house_info = []
# your code here
# ...
# for line in f.readlines():
...
# append to the list for every pass in the loop
house_info += np.array((c,a,r,hoa,ra,pt,fi))
# list-to-array conversion
house_info = np.array(house_info).reshape((len(house_info), 6))
return house_info
My code is as follows with comments. it runs fine until it comes to changing the value of a list item i.e. data[x][y] = something.
Tdata = cursor.fetchall() #Get data from MYSQL database
data = list(Tdata) #Convert into list...not sure if absolutely required
APIData = APIDataList()
MPLlat = 0.0
MPLLon = 0.0
RadiusOI = 15
for i in (range(0,len(data))):
MPLCount = 0
MPLlat = data[i][2]
MPLLon = data[i][3]
MPLCount = CountofbikesnearMPL(MPLlat, MPLLon, RadiusOI)
if MPLCount>0:
data[i][4] = MPLCount #ERROR: here is where the error is kicking in.
#get error "tuple' object does not support
#item assignment"
I really cant figure out why this is happening and have tried googling but with no success. Any help will be deeply appreciated.
Thanks in advance.
C
cursor.fetchall() returns a list of tuples.
That means that data[i] will be a tuple, which is by definition immutable. If you want to modify data[i], you will need to turn your tuples into lists
data = [list(row) for row in Tdata]
or replace the entire row via tuple concatenation
data[i] = data[i][:4] + (MPLCount,) + data[i][5:]
Maybe it is cleaner to write it using enumerate:
for i, elem in enumerate(data):
# MPLCount = 0 - I suppose it is unnecessary since you overwrite the value below
MPLlat = elem[2]
MPLLon = elem[3]
MPLCount = CountofbikesnearMPL(MPLlat, MPLLon, RadiusOI)
if MPLCount > 0:
data[i] = elem[:4] + (MPLCount,) + elem[5:]
Is there a reason you name variables and functions ThisWay? If not, it would be nice if you follow PEP8 and name them this_way. Anyway be consistent and don't mix two styles together.
Goal is to replace the second field of csv_line with new_item in an elegant way. This question is different from the topics listed by Rawing because here we are working with a different data structure, though we can use other topics to get inspired.
# Please assume that csv_line has not been imported from a file.
csv_line = 'unknown_item1,unknown_old_item2,unknown_item3'
new_item = 'unknown_new_item2'
goal = 'unknown_item1,unknown_new_item2,unknown_item3'
# Works but error prone. Non-replaced items could be inadvertently swapped.
# In addition, not convenient if string has many fields.
item1, item2, item3 = csv_line.split(',')
result = ','.join([item1, new_item, item3])
print(result) # unknown_item1,unknown_new_item2,unknown_item3
# Less error prone but ugly.
result_list = []
new_item_idx = 1
for i, item in enumerate(csv_line.split(',')):
result_list += [item] if i != new_item_idx else [new_item]
result = ','.join(result_list)
print(result) # unknown_item1,unknown_new_item2,unknown_item3
# Ideal (not-error prone) but not working.
csv_line.split(',')[1] = new_item
print(csv_line) # unknown_item1,unknown_old_item2,unknown_item3
The second item could be replaced using Python's CSV library by making use of io.StringIO() objects. This behave like files but can be read as a string:
import csv
import io
csv_line = 'unknown_item1,unknown_old_item2,unknown_item3'
new_item = 'unknown_new_item2'
row = next(csv.reader(io.StringIO(csv_line)))
row[1] = new_item
output = io.StringIO()
csv.writer(output).writerow(row)
goal = output.getvalue()
print(goal)
This would display goal as:
unknown_item1,unknown_new_item2,unknown_item3
l = csv_line.split(',')
l[1] = new_item
csv_line = ','.join(l)
In the line csv_line.split(',')[1] = new_item, you do not alter the csv_line variable at all. You need to assign the new list created with .split() to a variable before you can change the elements within it:
new_csv = csv_line.split(',')
new_csv[1] = new_item
print(','.join(new_csv))
This seems the most pythonic:
csv_line = 'unknown_item1,old_item2,unknown_item3'
old_index = 1
new_item = 'new_item2'
goal = 'unknown_item1,new_item2,unknown_item3'
items = csv_line.split(',')
items[old_index] = new_item
print(','.join(items))
print(goal)
Output:
unknown_item1,new_item2,unknown_item3
unknown_item1,new_item2,unknown_item3
The following code Ruby code will iterate the source string and produce a list of the cumulative words delimited by a '.' character, other than those after the last '.'.
For example, give a source string of 'Company.Dept.Group.Team' the result will be ...
["Company.Dept.Group", "Company.Dept", "Company"]
Given that a while loop in Python (I believe) will test only an expression and not a statement as shown below, how would one best write this in idiomatic Python?
#ruby
source = 'Company.Dept.Group.Team'
results = []
temp = source.clone
while (i = temp.rindex('.')) # test statement not supported in Python?
temp = temp[0...i]
results << temp
end
p results # >> ["Company.Dept.Group", "Company.Dept", "Company"]
The Python idiom is something like this:
while True:
i = temp.rindex('.')
if not i:
break
...
>>> source = 'Company.Dept.Group.Team'
>>> last = []
>>> [last.append(s) or '.'.join(last) for s in source.split('.')[:-1]]
['Company', 'Company.Dept', 'Company.Dept.Group']
To accomplish this in general, I'd probably do:
source = 'Company.Dept.Group.Team'
split_source = source.split('.')
results = ['.'.join(split_source[0:x]) for x in xrange(len(split_source) - 1, 0, -1)]
print results
A literal translation would be more like:
source = 'Company.Dept.Group.Team'
temp = source
results = []
while True:
i = temp.rfind('.')
if i < 0:
break
temp = temp[0:i]
results.append(temp)
print results
Or, if you prefer:
source = 'Company.Dept.Group.Team'
temp = source
results = []
try:
while True:
temp = temp[0:temp.rindex('.')]
results.append(temp)
except ValueError:
pass
print results
Or:
source = 'Company.Dept.Group.Team'
temp = source
results = []
i = temp.rfind('.')
while i > 0:
temp = temp[0:i]
results.append(temp)
i = temp.rfind('.')
print results
As you point out, the fact that you cannot treat assignment as an expression makes these cases a bit inelegant. I think the former cases(s) - i.e. "while True" - are more common than the last one.
For more background, this post looks pretty good: http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm
If you get used to Python you see list comprehensions and iterators/generators everywhere!
Python could be
source = 'Company.Dept.Group.Team'
# generate substrings
temp = source.split(".")
results = [".".join(temp[:i+1]) for i,s in enumerate(temp)]
# pop the team (alternatively slice the team out above)
results.pop()
# reverse results
result.reverse()
print result # should yield ["Company.Dept.Group", "Company.Dept", "Company"]
but most probably there are more idiomatic solutions ...
I would do
>>> import re
>>> source = 'Company.Dept.Group.Team'
>>> results = [source[:m.start()] for m in re.finditer(r"\.", source)]
>>> results
['Company', 'Company.Dept', 'Company.Dept.Group']
(use reversed(results) if you want the order to be reversed).
A more or less literal translation of your code into Python would be
source = 'Company.Dept.Group.Team'
results = []
temp = source
while True:
try:
i = temp.rindex('.')
temp = temp[:i]
results.append(temp)
except ValueError:
break
print(results)