Accessing a DataFrame inside of a class - python

I have created a DataFrame inside of a class but I am having trouble using it outside of the class or even calling it. How would I do that? I just want to print the DataFrame outside of the class.
class Youpi(Baseball, Soccer):
def __init__(self):
Baseball.__init__(self, self)
self.Random_df = pd.DataFrame(columns = ["Hot-Dogs"])
def Attendance(self, hot_dogs):
dictionary = {"Hot-Dogs":5}
self.Random_df = self.Random_df.append(dictionary, ignore_index=True)
return self.Random_df
Desired output:
// instruction to print the dataframe here
Output:
Hot-Dogs
5

I would try print(dictionary.Attendance)

Related

Returning DataFrame from one class to another class

I am trying to create 2 python classes, class CsvtoDataFrame for moving data from csv to DataFrame. and class DataFrametoDB from Dataframe to database. When I am trying to return the dataframe from CsvtoDataFrame and print it. It says "<main.CsvtoDataFrame object at 0x00981890>" How can I see the data of the dataframe outside the CsvtoDataFrame . I need help in this. Please!
import pandas as pd
class CsvtoDataFrame:
global pd_sales
def init(self,FileName):
self.FileName = FileName
pd_sales=pd.read_csv(FileName)
#print(pd_sales)
def ReturnFile(self):
return pd_sales
class DataFrametoDB:
def init(self,obj):
self.pd_sales=obj.pd_sales
print(self.pd_sales)
df=CsvtoDataFrame('test.csv')
print(df)enter image description here
In order to return pd_sales, you may need to create another function, insteading of doing in def init(self, FileName).
import pandas as pd
class CsvtoDataFrame:
global pd_sales
def __init__(self,File):
self.FileName = File
#print(pd_sales)
def readcvs(self):
pd_sales=pd.read_csv(self.FileName)
return pd_sales;
class DataFrametoDB:
def __init__(self,obj):
self.pd_sales=obj.pd_sales
print(self.pd_sales)
df=CsvtoDataFrame('test.csv')
df2=df.readcvs()
print(df2)

self.variable_name vs variable_name in method inside python class

Both versions of the code are working. I am trying to understand the difference between self.data_as_csv vs data_as_csv.
In which scenario each of them is useful over the another.
Version 1:
import pandas as pd
class test_class:
def __init__(self, inputFile):
self.file = inputFile
def generate_csv(self):
self.data_as_csv = pd.read_csv(self.file)
return self.data_as_csv
x = test_class("out.csv")
df = x.generate_csv()
print(df)
Version 2:
import pandas as pd
class test_class:
def __init__(self, inputFile):
self.file = inputFile
def generate_csv(self):
data_as_csv = pd.read_csv(self.file)
return data_as_csv
x = test_class("out.csv")
df = x.generate_csv()
print(df)
using as self, you have access to the variable like this, so if you needed access to the data from the class, it would be useful in that case:
x.data_as_csv
Out[1456]:
Empty DataFrame
Columns: [P234, Dog, Billy, No, No.1, D32432432, Lost, 01/09/2018, 28/08/2019, return to owner, 123 Fake Drive, LS34 1LE]
Index: []
using self. will allow you to access to this variable from any method of your class, that means u can have your 'global' variable available only in current class and only for current instance

How Do I Pass One List From A Class To Another Class?

I am new to using multiple classes in python and I am trying to create a Stock class that holds all the data for a single stock. However, when I try to do the basic initialization of the Stock class, the data variable registers as having no data. How do I fix this, and what am I doing wrong?
Class one
import Stock
stock = Stock.Stock("MSFT")
print(stock.data)
Class two
class Stock():
data = []
def __init__(self, ticker):
self.ticker = ticker
from yahoo_historical import Fetcher
chart = Fetcher(ticker, [2019, 1, 1], [2019, 6, 1])
data = chart.getHistorical()
Output: []
When you do data = chart.getHistorical() you are creating a new local variable, not setting that variable data = [] over there.
You need to scope to self so doing self.data = chart.getHistorical() would suffice for your problem.
Also note that using lists as class variables are danger. When you do
class Foo:
bar = []
And then
foo1 = Foo()
foo2 = Foo()
foo1.bar.append('Hello from foo1')
print(foo2.bar)
You would expect that this would print [] but will print ['Hello from foo1']. The problem here os that both instances have a property bar pointing to the same array object, when you modify this object both see the modification. For you case you can just drop the data = [] at class scope and keep with the self.data = ... at method scope
I hope that this helps

Adding a new object to a class with user-input(input) in python

I am trying to add new objects to a class(emne) but the new instances of the class needs to be created using user input. So i need a way to be able to chose the name for the object and set some of the values of the objects with user input.
I have already tried to create a function that passes the value of the user input into a x = emner(x) to create it but it only returns:
AttributeError: 'str' object has no attribute 'fagKode'
so i think my issue is that the value of the input is created as a string so that it is not understood as a way to create the function
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne():
nyttEmne = input("test:")
nyttEmne=Emne(nyttEmne)
expected result is that the code creates a new instance of the class.
If by choosing a name you mean your fagKode attribute, what you need is:
fagKode = input('Enter code: ')
Emne(fagKode)
You're adding the instances of Enme to the list in the constructor, so you don't need to save them to a variable.
Alternatively, you can handle that in the function:
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
def leggTilEmne():
nyttEmne = input("test:")
enme.append(Emne(nyttEmne))
I'm not sure what exactly you are asking, since you haven't responded to the comments. So,
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne(self, value): # <--- is this what you want
self.nyttEmne= Emne(value)
This is an example of when to use a class method. __init__ should not be appending to a global variable, though. Either 1) have the class method append to a class attribute, or 2) have it return the object and let the caller maintain a global list.
emne = []
class Emne:
emne = []
def __init__(self, fag_kode):
self.fag_kode = fag_kode
self.karakter = ""
#classmethod
def legg_til_emne_1(cls):
nytt_emne = input("test:")
cls.emne.append(cls(nytt_emne))
#classmethod
def legg_til_emne_2(cls):
nyttEmne = input("test:")
return cls(nyttEmne)
Emne.legg_til_emne_1() # Add to Emne.emne
e = Emne.legg_til_emne_2()
emne.append(e)

Python classes from a for loop

I've got a piece of code which contains a for loop to draw things from an XML file;
for evoNode in node.getElementsByTagName('evolution'):
evoName = getText(evoNode.getElementsByTagName( "type")[0].childNodes)
evoId = getText(evoNode.getElementsByTagName( "typeid")[0].childNodes)
evoLevel = getText(evoNode.getElementsByTagName( "level")[0].childNodes)
evoCost = getText(evoNode.getElementsByTagName("costperlevel")[0].childNodes)
evolutions.append("%s x %s" % (evoLevel, evoName))
Currently it outputs into a list called evolutions as it says in the last line of that code, for this and several other for functions with very similar functionality I need it to output into a class instead.
class evolutions:
def __init__(self, evoName, evoId, evoLevel, evoCost)
self.evoName = evoName
self.evoId = evoId
self.evoLevel = evoLevel
self.evoCost = evoCost
How to create a series of instances of this class, each of which is a response from that for function? Or what is a core practical solution? This one doesn't really need the class but one of the others really does.
A list comprehension might be a little cleaner. I'd also move the parsing logic to the constructor to clean up the implemenation:
class Evolution:
def __init__(self, node):
self.node = node
self.type = property("type")
self.typeid = property("typeid")
self.level = property("level")
self.costperlevel = property("costperlevel")
def property(self, prop):
return getText(self.node.getElementsByTagName(prop)[0].childNodes)
evolutionList = [Evolution(evoNode) for evoNode in node.getElementsByTagName('evolution')]
Alternatively, you could use map:
evolutionList = map(Evolution, node.getElementsByTagName('evolution'))
for evoNode in node.getElementsByTagName('evolution'):
evoName = getText(evoNode.getElementsByTagName("type")[0].childNodes)
evoId = getText(evoNode.getElementsByTagName("typeid")[0].childNodes)
evoLevel = getText(evoNode.getElementsByTagName("level")[0].childNodes)
evoCost = getText(evoNode.getElementsByTagName("costperlevel")[0].childNodes)
temporaryEvo = Evolutions(evoName, evoId, evoLevel, evoCost)
evolutionList.append(temporaryEvo)
# Or you can go with the 1 liner
evolutionList.append(Evolutions(evoName, evoId, evoLevel, evoCost))
I renamed your list because it shared the same name as your class and was confusing.

Categories

Resources