Python not getting the right value in an Excel cell - excel

I want to color the interior of a cell according to it's content, however when I'm accessing its value I'm always getting '1.0', the value is calculated.
Colorisation code :
def _colorizeTop10RejetsSheet(self):
"""Colore les position de la page "Top 10 Rejets" """
start_position = (5, 12)
last_line = 47
for x in range(start_position[0], last_line+1):
current_cell = self.workbook.Sheets("Top 10 Rejets").Cells(x, start_position[1])
current_cell.Interior.Color = self._computePositionColor(current_cell.Value)
def _computePositionColor(self, position):
"""Colore les position de 1 a 5 en rouge de et 6 a 10 en orange"""
if position < 6:
return self.RED
elif position < 11:
return self.ORANGE
else:
return self.WHITE
Excel cell code :
=SI(ESTNA(RECHERCHEV(CONCATENER(TEXTE($F23;0);TEXTE($G23;"00");$H23;$I23);Données!$J:$P;7;FAUX));MAX(Données!$P:$P);RECHERCHEV(CONCATENER(TEXTE($F23;0);TEXTE($G23;"00");$H23;$I23);Données!$J:$P;7;FAUX))
How could I get the calculated value?
I'm using python 2.7 and I'm communicating with Excel through win32com
Thanks

Adding this to the beginning of the _colorizeTop10Rejets method did the trick
self.xl.Calculate()
self.xl is the object returned by win32.Dispatch('Excel.Application')

Related

i am getting index out of range error its for my college project

dept=[che,civil,mech,it,eee,ec]
hall_allo=[]
number_cand=len(che+civil+mech+it+eee+ec)
print(number_cand)
#for generating hall
i=0
z=0
for j in range(1,int(number_cand/21)+2):#to generate hall
if(j==int(number_cand/21)+2):
for k in range(1,number_cand%20):
halloall={
"Reg":dept[i][z],
"Hall_no":j,
"Seat":k
}
hall_allo.append(hall_allo)
i=i+1
else:
for k in range(1,21):#seat
if(i==7):
i=0
z=z+1
else:
halloall={
"Reg":dept[i][z],
"Hall_no":j,
"Seeat":k
}
hall_allo.append(halloall)
i=i+1
print(hall_allo)
in the above mentioned code am getting index out of range error its for my college project
the project is exam seating arrangement system
che ,civil,it,mech,eee,ec are a list of students

Pandas string encoding when retrieving cell value

I have the following Series:
s = pd.Series(['ANO DE LOS BÃEZ MH EE 3 201'])
When I print the series I get:
0 ANO DE LOS BÃEZ MH EE 3 201
But when I get the cell element I get an hexadecimal value in the string:
>>> s.iloc[0]
'ANO DE LOS BÃ\x81EZ MH EE 3 201'
Why does this happens and how can I retrieve the cell value and get the string: 'ANO DE LOS BÃEZ MH EE 3 201'?
Even though I am not really sure where the issue arised I Could solve it by using the unidecode package.
output_string = unidecode(s.iloc[0])

Failing to use sumproduct on date ranges with multiple conditions [Python]

From replacement data table (below on the image), I am trying to incorporate the solbox product replace in time series data format(above on the image). I need to extract out the number of consumers per day from the information.
What I need to find out:
On a specific date, which number of solbox product was active
On a specific date, which number of solbox product (which was a consumer) was active
I have used this line of code in excel but cannot implement this on python properly.
=SUMPRODUCT((Record_Solbox_Replacement!$O$2:$O$1367 = "consumer") * (A475>=Record_Solbox_Replacement!$L$2:$L$1367)*(A475<Record_Solbox_Replacement!$M$2:$M$1367))
I tried in python -
timebase_df['date'] = pd.date_range(start = replace_table_df['solbox_started'].min(), end = replace_table_df['solbox_started'].max(), freq = frequency)
timebase_df['date_unix'] = timebase_df['date'].astype(np.int64) // 10**9
timebase_df['no_of_solboxes'] = ((timebase_df['date_unix']>=replace_table_df['started'].to_numpy()) & (timebase_df['date_unix'] < replace_table_df['ended'].to_numpy() & replace_table_df['customer_type'] == 'customer']))
ERROR:
~\Anaconda3\Anaconda4\lib\site-packages\pandas\core\ops\array_ops.py in comparison_op(left, right, op)
232 # The ambiguous case is object-dtype. See GH#27803
233 if len(lvalues) != len(rvalues):
--> 234 raise ValueError("Lengths must match to compare")
235
236 if should_extension_dispatch(lvalues, rvalues):
ValueError: Lengths must match to compare
Can someone help me please? I can explain in comment section if I have missed something.

Comparing two dataframes with a function (without common indices)

I have 2 pandas data frames, restaurants:
Lat Long Name
0 43.599503 1.440678 Le Filochard
1 43.602369 1.447368 Le Wallace
2 43.603838 1.435186 Chez Tonton, Pastis Ô Maître
and hotels:
Lat Long Name
0 43.603779 1.444004 Grand Hôtel de l'Opéra
1 43.599482 1.441207 Hôtel Garonne
2 43.549924 1.499821 Ibis Styles
And 1 function distance(origin,destination) with origin = (lat,long) coord.
I am trying to apply the function to the 2 data frames to calculate for each row of the first data frame the number of item from the second data frame for which the distance is inferior to 0.2 ...
I'm trying the apply map function but do not manage to perform it with the 2 data frames; do I need to merge them?
Would this work for you?
Just need to correct function for distance
hotels=pd.DataFrame([[43.599503, 1.440678, 'Le Filochard'],
[43.602369, 1.447368, 'Le Wallace'],
[43.603838, 1.435186, 'Chez Tonton, Pastis Ô Maître']],
columns=['Lat', 'Long', 'Name'])
restaurants=pd.DataFrame([[43.603779, 1.444004, "Grand Hôtel de l'Opéra"],
[43.599482, 1.441207, 'Hôtel Garonne'],
[43.549924, 1.499821, 'Ibis Styles']],
columns=['Lat', 'Long', 'Name'])
hotels['Nearby Resaurants'] = hotels.apply(lambda h: list(restaurants[((restaurants.Lat-h.Lat)**2+(restaurants.Long-h.Long)**2)<0.005].Name), axis=1)
print(hotels)
Lat Long Name \
0 43.599503 1.440678 Le Filochard
1 43.602369 1.447368 Le Wallace
2 43.603838 1.435186 Chez Tonton, Pastis Ô Maître
Nearby Resaurants
0 [Grand Hôtel de l'Opéra, Hôtel Garonne]
1 [Grand Hôtel de l'Opéra, Hôtel Garonne]
2 [Grand Hôtel de l'Opéra, Hôtel Garonne]
EDIT:
Modification to handle function, filtering of hotels also by using lambda function
def distance(X,Y):
return((X[0]-X[1])**2+(Y[0]-Y[1])**2)
hotels['Nearby Resaurants'] = hotels.apply(lambda h: list(restaurants.loc[restaurants.apply(lambda r: distance((r.Lat,h.Lat),(r.Long,h.Long))<0.005, axis=1)].Name), axis=1)
print(hotels)

Adding an integer after each printed line from dictonaries

I am learning how to program in Python 3 and I am working on a project that lets you buy a ticket to a movie. After that you can see your shopping cart with all the tickets that you have bought.
Now, I want after each printed line to add a integer.
For example: 1. Movie1 , 2. Movie2 , etc..
Here is my code that I use to print the films:
if choice == 3:
#try:
print("Daca doresti sa vezi ce filme sunt valabile, scrie exit.")
bilet = str(input("Ce film doresti sa vizionezi?: ").title())
pret = films[bilet]["price"]
cumperi = input("Doresti sa adaugi in cosul de cumparaturi {}$ (y/n)?".format(bilet)).strip().lower()
if cumperi == "y":
bani[0] -= pret
cos.append(bilet)
if choice == 4:
print (*cos, sep="\n")
You can use an integral variable and increase it's value whenever you perform a task.
example set count = 0 and when you does a task place this there count += 1.

Resources