df_store_index_list = df_store.index.tolist()
df_store_column_list = df_store[column].tolist()
list_to_be_returned = []
for i in range(len(df_store_index_list)):
list_to_be_returned.append([df_store_index_list[i], df_store_column_list[i]])
# return list_to_be_returned
return [[df_store_index_list[i], df_store_column_list[i]] for i in range(len(df_store_index_list)) ] not working!!!!
I have a function that returns a two-dimensional list.
Problem: the list comprehension on the last line is giving me an error saying "df_store_index_list is not defined".
Solution: I created my own list (list_to_be_returned) and did a custom for loop and it's working fine. It has a value (list_to_be_returned). But I was just wondering, why is the list comprehension not working?
here is the complete code
#classmethod
def store_specific_info_string(cls, store_name, column, ascending=False):
"""
Brief
- filter for specific store
Description
- obtain sum of column based on specific `Store_Name`
Parameter
- store_name : inside the `Store_Name` column
- ascending : True or False
- column : sum of what column? (Total_Sales, Total_Profit)
Return Value(s)
- tuple of name(Item_Description) and sum of column passed based on name.
"""
# filter the store by store name
df_store = cls.dataframe[ cls.dataframe[ "Store_Name" ] == store_name]
df_store = df_store.groupby("Item_Description").sum()[[column]]
# sort them by the column(integer)
df_store.sort_values(column,ascending=ascending ,inplace=True)
df_store_index_list = df_store.index.tolist()
df_store_column_list = df_store[column].tolist()
list_to_be_returned = []
for i in range(len(df_store_index_list)):
list_to_be_returned.append([df_store_index_list[i], df_store_column_list[i]])
return list_to_be_returned
# return [[df_store_index_list[i], df_store_column_list[i]] for i in range(len(df_store_index_list)) ] not working!!!!
here is a pdb initiated
inside pdb
Based on your comment it seems that you really want the list of list format with a list comprehension. Here is another way to do your list comprehension (but that doesn't explain why yours didn't work)
column_serie = df_store[column]
[[idx, value] for idx,value in column_serie.iteritems()]
Related
I have python code that uses arcpy.SearchCursor to look for unique values in a field (Native_Species, in my case), and put them into a list. Then I use list comprehension to remove None values, sort the list, and print. This code works.
# Create empty list, use .SearchCursor to populate list with unique values
myList = []
rows = arcpy.SearchCursor(monitoring)
for row in rows:
if row.Native_Species not in myList:
myList.append(row.Native_Species)
# Use list comprehension to remove None values in list
res = [i for i in myList if i]
# Sort list and print
res.sort()
print(*res, sep = '\n')
I would like to put this code into a function, where I can list only unique values across multiple fields in a given feature class. This is what I have tried:
def listUnique(fc, fields):
myList = []
with arcpy.da.SearchCursor(fc, fields) as cursor:
for row in cursor:
if row.fields not in myList:
myList.append(row.fields)
res = [i for i in myList if i]
res.sort()
print(*res, sep = '\n')
This gives me an error "'tuple' object has no attribute 'fields'".
How should I put my working code into a function, where I can specify a given input feature class, and a list of fields within that feature class, and get back a list of only unique values across those fields?
Thank you!
The output is not real pretty. Might be more useful to create a unique value list for every feature class column. Hopefully this will give you some ideas to get what you need.
import arcpy
# set the workspace to the geodatabase the feature class is in
arcpy.env.workspace = r'\path\to\your\geodatabase.gdb'
def uniqueValues(fc):
# create a list of unique values from all rows and columns in a feature class
#create an empty list to store all values in the feature class
tableList = []
#Get all values in the feature class and append them to tableList
fcList = arcpy.ListFeatureClasses(fc)
for fc in fcList:
with arcpy.da.SearchCursor(fc, "*") as cursor:
for row in cursor:
for value in row:
tableList.append(value)
print('The list length of all values is ' + str(len(tableList)))
# Create an empty list to store the unique values in the feature class
uniqueList = []
# use set to drop duplicates
uniqueSet = set(tableList)
print('The list length of unique values is ' + str(len(uniqueSet)))
# put the items from the set back into a list. add all values to the list as strings to avoid data type problems
for item in uniqueSet:
uniqueList.append(str(item))
# remove none values from the list
uniqueList = [i for i in uniqueList if i]
# sort the list
uniqueList = sorted(uniqueList)
print(*uniqueList, sep = '\n')
# call the function and enter the name of the feature class as the parameter
uniqueValues('Enter Feature Class Name')
I am struggling with an assignment for a course I have entered.
Create a function which returns a list of countries the number of cases is equal to one:
Hint: you can use the zip() function in Python to iterate over two lists at the same time.
So the prior question was to get the number of countries which had a single case of corona.
There was 7 countries as the output - and the following worked for that.
# Add your code below
def single_case_country_count(data):
item = data['Total Cases']
count = item.count(1)
if count == 0:
print('None found')
return count
# pass
I am however struggling with the second portion returning the names of these said 7 countries.
type(latest) is showing dict
i wrote this code
assuming i will have a dictionary of only cases where it is equal to 1 and
the original list; group them through the zipped function and then finally only show the list of countries.
def single_case_countries(data):
cases = data['Total Cases'] == 1
names = data['Country']
zipped = zip(names,cases)
final = list(zipped)
return final['Country']
# pass
TypeError: 'bool' object is not iterable
The clear issue here is that I cannot filter on the dictionary using " cases = data['Total Cases'] == 1" as it returns back a boolean.
Was wondering if there is some advice (especially filtering on a dictionary for a specific value
I managed to solve this with the following code:
def single_case_countries(data):
countries = []
for country,cases in zip(data["Country"],data["Total Cases"]):
if cases == 1:
countries.append(country)
return countries
I have a list of personal data(id_code,birth_year,born_in) and i want to sort the any arrays in list but i have a problem in this work.
my list data :
data = [
'id_code:3211238576;birth_year:1350;born_in:Boushehr',
'id_code:9801233575;born_in:Argentina;birth_year:1360',
'born_in:Portugal;id_code:0219206431;birth_year:1358',
'id_code:0021678913;born_in:Shiraz;birth_year:1120',
'id_code:1101102135;born_in:Gilan;birth_year:1152',
]
The code I wrote and has an bug:
for i in data:
s = ''.join(sorted(i))
print(s)
my code output:
01112233355678:::;;B___abbcddeeehhhiiinnooorrrrstuy
00112333556789:::;;A___aabbcddeeeghiiiinnnnoorrrrtty
00111223345689:::;;P___aabbcddeeghiiilnnooorrrrttuy
00011112236789:::;;S___aabbcddeehhiiiinnoorrrrtyz
00111111122355:::;;G___aabbcddeehiiiilnnnoorrrty
But! The code to i want to have in output(True answer):
id_code:3211238576,born_in:Boushehr,birth_year:1350
id_code:9801233575,born_in:Argentina,birth_year:1360
id_code:0219206431,born_in:Portugal,birth_year:1358
id_code:0021678913,born_in:Shiraz,birth_year:1120
id_code:1101102135,born_in:Gilan,birth_year:1152
Please help me to solve this problem
Assuming you want your fields to be in specific order, try this one: (I put comments in code for clarification):
data = [
'id_code:3211238576;birth_year:1350;born_in:Boushehr',
'id_code:9801233575;born_in:Argentina;birth_year:1360',
'born_in:Portugal;id_code:0219206431;birth_year:1358',
'id_code:0021678913;born_in:Shiraz;birth_year:1120',
'id_code:1101102135;born_in:Gilan;birth_year:1152',
]
def sorter(x: str):
# getting the field name
field = x.split(':')[0]
# returning it's index from "sorted_by" list
return sorted_by.index(field)
# The index of these fields will be used for sorting in "sorter" function.
sorted_by = ['id_code', 'born_in', 'birth_year']
result = []
for item in data:
# splitting the fields
splited = item.split(';')
splited.sort(key=sorter)
# building the line back and append it
result.append(';'.join(splited))
for i in result:
print(i)
output :
id_code:3211238576;born_in:Boushehr;birth_year:1350
id_code:9801233575;born_in:Argentina;birth_year:1360
id_code:0219206431;born_in:Portugal;birth_year:1358
id_code:0021678913;born_in:Shiraz;birth_year:1120
id_code:1101102135;born_in:Gilan;birth_year:1152
Now you can easily change the fields order in sorted_by list and see the result.
Try
out = [';'.join(reversed(sorted(x.split(';')))) for x in data]
print(out)
This takes every element of the data list and splits it in three strings, each of which contains one of the three attributes. Then, it arranges the three strings in reversed alphabetical order and joins them back into one string, separated by ';'
I have two values number and sys_id. I have made seperate list for both of the values. How can save it in any other data structure like dictionary, or something else because i those list of number and sys_id are related. I am doing it in Python
Below Is the code what i have done
ticket_num.append(resp['result'][idx]['number'])
sys_id.append(resp['result'][idx]['sys_id']) ```
This is making two list one for ticket_num and sys_id. As Ticket number and sys_id are related for example ticket_num = ['INC00012','INC00013','INC00014' ] ,
sys_id = ['644323432sfasesdf213', '644323432dfgdfkdskrwwr', 'f283044423fdldsf09']
As this list are related like ticket_num[0] is directly link with sys_id[0]
So can i make a dictionary that contains ticket_num, sys_id directly without creating lists(for e.g. : {ticket_num : '...' , sys_id = '....' , ..... }
Use zip with dict
Ex:
ticket_num = ['INC00012','INC00013','INC00014' ]
sys_id = ['644323432sfasesdf213', '644323432dfgdfkdskrwwr', 'f283044423fdldsf09']
print(dict(zip(ticket_num, sys_id)))
Output:
{'INC00012': '644323432sfasesdf213',
'INC00013': '644323432dfgdfkdskrwwr',
'INC00014': 'f283044423fdldsf09'}
Welcome to Stackoverflow.
Do you actually need the lists of ticket numbers and IDs? If not that you could instead consider building the structure you need instead of the lists.
You don't say whether you want to be able to look up IDs from ticket numbers or vice versa. This solution allows you to do either:
idx_from_ticket = {}
ticket_from_idx = {}
# In the loop that produces the values, instead of the current appends ...
temp = resp['result'][idx]
idx = temp['sys_id]
number = temp['number']
idx_from_ticket[number] = idx
ticket_from_idx[idx] = number
The two dictionaries can then be used to correlate the IDs and ticket numbers. If you want to actually do something else then I hope this code gives you enough clues.
If you do already have the lists and want to retain them then the zip function is your friend.
idx_from_ticket = dict(zip(ticket_num, sys_id))
ticket_from_idx = dict(zip(sys_id, ticket_num))
zip, when called with two argument, yields a sequence of two-element tuples, which the
dict function assumes are key/value pairs.
I have a function below which searches for a dictionary key match using an inputted function parameter. If a key match is found I want the value at index 1 (the team) to change to the desired team inputted when the function is called:
dict1 = {'Messi' : ('Argentina','Barcelona'), 'Ronaldo' : ('Portugal','Juventus'), 'Robben': ('Netherlands','Bayern')}
def setNewTeam(plyr, newTeam):
for x in dict1:
if plyr == x:
dict1[plyr][1] = newTeam
setNewTeam('Messi', 'Manchester')
When I run this code however, I get:
TypeError: 'tuple' object does not support item assignment
I know this must be because tuples are not mutable but there must be a way of making this work since i'm working with dictionaries, can anyone lend a hand here?
Thank you!
As the error message says, you cannot assign new items to tuples because tuples are immutable objects in python.
my_tup = (1,2,3)
my_tup[0] = 2 # TypeError
What you could do is using a list instead:
dict1 = {'Messi' : ['Argentina','Barcelona'], 'Ronaldo' : ['Portugal','Juventus'], 'Robben': ['Netherlands','Bayern']}
def setNewTeam(plyr, newTeam):
for x in dict1:
if plyr == x:
dict1[plyr][1] = newTeam
setNewTeam('Messi', 'Manchester')
Note how lists are created using [] while tuples use ().
dict1 = {'Messi' : ('Argentina','Barcelona'), 'Ronaldo' : ('Portugal','Juventus'), 'Robben': ('Netherlands','Bayern')}
def setNewTeam(plyr, newTeam):
for x in dict1:
if plyr == x:
dict1[plyr] = (dict1[plyr][0], newTeam)
setNewTeam('Messi', 'Manchester')
Since you want to update values, tuple is not the good data-structure. You should use a list.
If you still want to use a tuple, you can build a brand new tuple with :
dict1[plyr] = (dict1[plyr][0], newTeam)
dict1[plyr][1] = newTeam
Tuples are immutable, but lists are not. You can do something like:
list1 = list(dict1[plyr])
list1[1] = newTeam
dict1[plyr] = tuple(list1)
It will add the newTeam to your desired location, and it will still be a tuple.