I'm trying to print a select row and columns from a spreadsheet, however when I call on the spreadsheet dataframe attribute it fails to print state that the name dataframe is not defined. where have I gone wrong?
import pandas
class spreadsheet:
def __init__(self, location, dataframe, column, rows):
self.location = ('Readfrom.xlsx')
self.dataframe = pandas.read_excel(location)
self.column = 2
self.rows = 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29
a = dataframe.iloc[column,[rows]]
print(a)
You should instantiate an object from the Spreadsheet class and then access the attribute of the instance. You can learn more about Object-Oriented Programming in Python here.
I think that what you want to do in your code is something like the code below.
import pandas
class Spreadsheet:
def __init__(self, location):
self.location = location
self.dataframe = pandas.read_excel(location)
sp = Spreadsheet(location="Readfrom.xlsx")
rows = [4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29]
a = sp.dataframe.iloc[rows, 2]
print(a)
I think you have an indentation problem.
Your dataframe is a parameter of your spreadsheet constructor method and you try to access it even from outside the class.
To access the dataframe variable u have to move your code a = dataframe.iloc[column,[rows]] inside your __init__ method or you need to create a spreadsheet object first and access it via this object.
EDIT:
On second thoughts i think you should check out the basics how to use classes in Python.
You don't use the parameters of the __init__ so why du you have them?
dataframe is only accessible by a spreadsheet object
This code should fix your problem but i recommend to go through some basic tutorials to understand how exactly classes and objects are working:
import pandas
class spreadsheet:
def __init__(self):
self.location = ('Readfrom.xlsx')
self.dataframe = pandas.read_excel(self.location)
self.column = 2
self.rows = 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29
s = spreadsheet()
a = s.dataframe.iloc[s.column,[s.rows]]
print(a)
Related
class CustomOrderFilter(OrderingFilter):
allowed_custom_filters = ['target_item__type_service', 'target_item__level', 'target_item__room__name',
'client__user_full_name', 'designer__user_full_name', 'status', 'date_due_decorist',
'target_item__date_answered']
def get_ordering(self, request, queryset, view):
params = request.query_params.get(self.ordering_param)
if params:
fields = [param.strip() for param in params.split(',')]
ordering = [f for f in fields if f.lstrip('-') in self.allowed_custom_filters]
if ordering:
return ordering
return self.get_default_ordering(view)
def filter_queryset(self, request, queryset, view):
order_fields = []
ordering = self.get_ordering(request, queryset, view)
if not ordering:
return queryset
order_fields.append(ordering[0])
if 'status' in order_fields or '-status' in order_fields:
ids = [0, 1, 2, 18, 3, 6, 9, 7, 21, 5, 8, 11, 12, 10, 14, 15, 16, 20, 4, 13, 17]
rev_ids = [11, 8, 5, 21, 7, 9, 6, 3, 18, 2, 1, 0, 12, 10, 14, 15, 16, 20, 4, 13, 17]
if '-status' in order_fields:
order = Case(*[When(status=id, then=pos) for pos, id in enumerate(rev_ids)])
else:
order = Case(*[When(status=id, then=pos) for pos, id in enumerate(ids)])
return queryset.order_by(order)
if '-date_due_decorist' in order_fields:
return queryset.order_by(F('date_due_decorist').desc(nulls_last=True))
elif 'date_due_decorist' in order_fields:
return queryset.order_by(F('date_due_decorist').asc(nulls_last=True))
return queryset.order_by(ordering[0])
In custom ordering django, I am getting error as "asc() got an unexpected keyword argument 'nulls_last' ". I want to show null values always at last in date_due_decorist column while sorting. Please let me know if django version 1.10 supports 'nulls_last' or not.
If not support then let me know how can this be done?
import re
import os
import sys
class Marks:
def __init__(self):
self.marks = []
self.marks_file = '/root/projectpython/mark.txt'
def loadAll(self):
file = open(self.marks_file, 'r')
for line in file.readlines():
name,math,phy,chem = line.strip().split()
name=name
math=int(math)
phy=int(phy)
chem=int(chem)
self.marks=[name,math,phy,chem]
print(self.marks)
file.close()
def percent(self):
dash = '-' * 40
self.loadAll()
for n in self.marks:
print(n)
Book_1 = Marks()
Book_1.percent()
output:-
['gk', 50, 40, 30]
['rahul', 34, 54, 30]
['rohit', 87, 45, 9]
rohit
87
45
9
but i want to print all value in tabular format,it showing only last record.
is it correct method to use list to store student data name and marks.
problem here is with the line read
self.marks=[name,math,phy,chem]
this will keep reinitializing the list each time mark is read
instead use:
self.marks.append([name,math,phy,chem])
You continue to initialize the list in the for statement
and declare it so that only the array value of the last line is reflected.
I think you can remove the initialization statement and process it as an append.
import re
import os
import sys
class Marks:
def __init__(self):
self.marks = []
self.marks_file = '/root/projectpython/mark.txt'
def loadAll(self):
file = open(self.marks_file, 'r')
for line in file.readlines():
name,math,phy,chem = line.strip().split()
name=name
math=int(math)
phy=int(phy)
chem=int(chem)
self.marks.append(name)
self.marks.append(math)
self.marks.append(phy)
self.marks.append(chem)
# self.marks=[name,math,phy,chem]
print(self.marks)
file.close()
def percent(self):
dash = '-' * 40
self.loadAll()
for n in self.marks:
print(n)
Book_1 = Marks()
Book_1.percent()
Make self.marks=[name,math,phy,chem] as self.marks.append([name,math,phy,chem]).
Then easiest solution is to transpose the self.marks list and print them.
suppose your marks list is [['gk', 50, 40, 30],['rahul', 34, 54, 30],['rohit', 87, 45, 9]] then simply transpose it.
print(marks)
transposed=list(zip(*marks))
print(transposed)
for x in transposed:
print(x)
output :
[['gk', 50, 40, 30], ['rahul', 34, 54, 30], ['rohit', 87, 45, 9]] #marks list
[('gk', 'rahul', 'rohit'), (50, 34, 87), (40, 54, 45), (30, 30, 9)] #transposed list
('gk', 'rahul', 'rohit') # output the way you want
(50, 34, 87)
(40, 54, 45)
(30, 30, 9)
Its working now.
i was doing mistake earlier here only self.marks.append([name,math,phy,chem])
[['gk', 50, 40, 30], ['rahul', 34, 54, 30], ['rohit', 87, 45, 9]]
I connect my python to MySQL server with mySQL-Connector(in pyCharm) and i can read from server then write text file.This seems to be:
(1, 'PENELOPE', 'GUINESS', datetime.datetime(2006, 2, 15, 4, 34, 33))
(2, 'NICK', 'WAHLBERG', datetime.datetime(2006, 2, 15, 4, 34, 33))
(3, 'ED', 'CHASE', datetime.datetime(2006, 2, 15, 4, 34, 33))
(4, 'JENNIFER', 'DAVIS', datetime.datetime(2006, 2, 15, 4, 34, 33))
(5, 'JOHNNY', 'LOLLOBRIGIDA', datetime.datetime(2006, 2, 15, 4, 34, 33))
I need to change the commas which are between two areas from , to ~ i can find source code could you help me ?Which class I do change?
this is my python code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="2153417",
database="sakila"
)
tweets = open("keywords.txt", "w")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM actor")
with open("C:/Users/Erhan/PycharmProjects/MySQL/keywords.txt", "w", newline='') as f:
for row in mycursor:
print(row, file=f)
this is working correctly just need change commas(,) among name,surname and datetime
like this
(1~ 'PENELOPE' ~ 'GUINESS' ~ datetime.datetime(2006, 2, 15, 4, 34, 33))
(2~ 'NICK' ~ 'WAHLBERG' ~ datetime.datetime(2006, 2, 15, 4, 34, 33))
Assuming you want the string representation of all objects(e.g 2006-02-15 04:34:33) instead of the objects representations datetime.datetime(2006, 2, 15, 4, 34, 33), try this:
As per your requirement, try this:
print(' ~ '.join(map(repr, row)), file=f)
I would recommend to try directly writing to the file instead:
f.write(' ~ '.join(map(repr, row))
I have something like this where trade_date, effective_date and termination_date are date values:
tradedates = dict(((k, k.strftime('%Y-%m-%d'))
for k in (trade_date,effective_date,termination_date)))
I get this:
{datetime.date(2005, 7, 25): '2005-07-25',
datetime.datetime(2005, 7, 27, 11, 26, 38): '2005-07-27',
datetime.datetime(2010, 7, 26, 11, 26, 38): '2010-07-26'}
What I would like is:
{'trade_date':'2005-07-25','effective_date':'2005-07-27','termination_date':'2010-07-26'}
How do I achieve this?
Using vars:
>>> import datetime
>>>
>>> trade_date = datetime.date(2005, 7, 25)
>>> effective_date = datetime.datetime(2005, 7, 27, 11, 26, 38)
>>> termination_date = datetime.datetime(2010, 7, 26, 11, 26, 38)
>>>
>>> d = vars() # You can access the variable as d['name']
>>> tradedates = {
... name: d[name].strftime('%Y-%m-%d')
... for name in ('trade_date', 'effective_date', 'termination_date')
... }
>>> tradedates
{'effective_date': '2005-07-27', 'termination_date': '2010-07-26', 'trade_date': '2005-07-25'}
For something that size, I'd create the dict directly:
result = {
'trade_date': format(trade_date, '%Y-%m-%d'),
'effective_date': format(effective_date, '%Y-%m-%d'),
# etc....
}
I am not sure if I got your question right. But let me explain what I understood and my answer for that:
You know the variable names: trade_date,effective_date,termination_date
And they have data in them
You could easily do:
tradedates = dict()
for k in ('trade_date','effective_date','termination_date'):
tradedates[k] = eval(k).strftime('%Y-%m-%d') // eval will evaluate them as a variable name not as a string.
This will give you a final dict something like:
{
'trade_date': <date_string_according_to_the_format_above>
'effective_date': <date_string_according_to_the_format_above>
'termination_date': <date_string_according_to_the_format_above>
}
I'm using the collection.Counter function to create a dictionary of paths to its listing of its mime types in order. It's a great little module, however the Counter doesn't change it's values from path to path.
I have a dictionary called package_mime_types that each entry looks like this:
package_mime_types['/a/path/to/somewhere'] = [('text/plain'),('text/plain'),('application/msword')]...
As you can imagine, the values in that dictionary are very long. I'm trying to convert it to a listing like this:
package_mime_types['/a/path/to/somewhere'] = ['text/plain':780, 'application/msword':400, 'audio/mp3':30]
This is my little iteration that's supposed to do that:
for package_path, mime_types_list in package_mime_types.items():
c = collections.Counter(mime_types_list)
package_mime_types[package_path] = c
return package_mime_types
The end result works, but all the Counter arrays are the exact same for each path.
/path1/ relates to Counter({'text/plain': 2303, 'audio/x-wav': 90, 'text/html': 17, 'application/msword': 17, 'application/x-trash': 6, 'application/x-tar': 4, 'application/xml': 1, 'text/x-sh': 1})
/path2/ relates to Counter({'text/plain': 2303, 'audio/x-wav': 90, 'text/html': 17, 'application/msword': 17, 'application/x-trash': 6, 'application/x-tar': 4, 'application/xml': 1, 'text/x-sh': 1})
/path3/ relates to Counter({'text/plain': 2303, 'audio/x-wav': 90, 'text/html': 17, 'application/msword': 17, 'application/x-trash': 6, 'application/x-tar': 4, 'application/xml': 1, 'text/x-sh': 1})
/path4/ relates to Counter({'text/plain': 2303, 'audio/x-wav': 90, 'text/html': 17, 'application/msword': 17, 'application/x-trash': 6, 'application/x-tar': 4, 'application/xml': 1, 'text/x-sh': 1})
/path5/ relates to Counter({'text/plain': 2303, 'audio/x-wav': 90, 'text/html': 17, 'application/msword': 17, 'application/x-trash': 6, 'application/x-tar': 4, 'application/xml': 1, 'text/x-sh': 1})
Am I missing something with using the Counter?
I'm facepalming myself right now. It wasn't a problem with the Counter at all but rather the iteration I was doing to create the listing of the file types. I didn't make a new array each time the iteration was populating my dictionary. So all of the files were associated with each path.
def find_mimes(package_paths):
package_mime_types = {}
mime_types_list =[]
## Walking through directories looking for the mime types
for package_path in package_paths:
print(package_path, "is being walked through")
for root, dirs, files in os.walk(package_path, followlinks = True):
for file in files:
if mimetypes.guess_type(os.path.join(root, file)) != (None, None):
mime_types_list.append(mimetypes.guess_type(os.path.join(root, file))[0])
package_mime_types[package_path] = mime_types_list
See how mime_types_list is above the iteration? It was a static variable. Moving into the package_path loop fixed it.
def find_mimes(package_paths):
package_mime_types = {}
## Walking through directories looking for the mime types
for package_path in package_paths:
##Setting mime_types_list array back to empty for every path. (Duh)
##Now mime_types_list will be empty before the walking starts
mime_types_list =[]
print(package_path, "is being walked through")
for root, dirs, files in os.walk(package_path, followlinks = True):
for file in files:
if mimetypes.guess_type(os.path.join(root, file)) != (None, None):
mime_types_list.append(mimetypes.guess_type(os.path.join(root, file))[0])
package_mime_types[package_path] = mime_types_list