Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
x = 5
y = 8
I want to combine those variables and define an another variable, like:
z = 58
It depends on what you mean by "combine".
You can concatenate numbers as strings:
z = int(str(x) + str(y))
But you can also compute x * 10 + y:
z = x * 10 + y
This will give different results if y > 9, e.g. for x = 5 and y = 10, the first version will give 510, while the second version will give 60.
Convert them to strings and concatenate them, then convert them back to an integer:
z = int(str(x) + str(y))
If you're using Python 3.6 or later, this can be done quite concisely with format strings:
>>> x = 5
>>> y = 8
>>> z = int(f'{x}{y}')
>>> z
58
>>>
A more general solution would be something like:
>>> def join_ints(*args):
... return int(''.join(map(str, args)))
...
>>> join_ints(5, 6, 8, 3)
5683
>>>
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to to be able to something along the lines of:
for i in range(0, len(df), 4):
curr = pd.DataFrame()
vcch = int(df.loc[i, 'IN_CUSTOM_SELECT'])
icch = int(df.loc[i+1, 'IN_CUSTOM_SELECT'])
vccl = int(df.loc[i+2, 'IN_CUSTOM_SELECT'])
iccl = int(df.loc[i+3, 'IN_CUSTOM_SELECT'])
idlpwr = (vcch * icch) + (vccl * iccl)
idlpwr = idlpwr / (10**6)
where I do some calculations based on the specific values of columns in combinations of rows of 4.
If you're just working with a regular autonumbered index, one easy option is to reshape your data and use pandas vectorized operations for the math:
In [196]: df = pd.DataFrame({'IN_CUSTOM_SELECT': np.random.random(24)})
In [197]: reshaped = df.set_index([df.index.map(lambda x: x // 4), df.index.map(lambda x: x % 4)]).unstack()['IN_CUSTOM_SELECT']
In [198]: reshaped['idlpwr'] = ((reshaped[0] * reshaped[1]) + (reshaped[2] * reshaped[3])) / 10**6
In [199]: reshaped
Out[199]:
0 1 2 3 idlpwr
0 0.788758 0.853356 0.627796 0.355143 8.960487e-07
1 0.312111 0.602934 0.908984 0.046183 2.301622e-07
2 0.842201 0.507629 0.541432 0.592680 7.484218e-07
3 0.506601 0.605108 0.497627 0.362006 4.866923e-07
4 0.308097 0.991945 0.822433 0.272082 5.293851e-07
5 0.573716 0.852356 0.009606 0.961437 4.982462e-07
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I need to create a list in Python from a minimum and a maximum value. Half of the list needs to go up, and the other half needs to go down. Here's what I'm doing for now:
random_data = np.random.uniform(min_value, max_value, 6))
up_data = np.sort(random_data)
down_data = -np.sort(-random_data)
df = np.concatenate((up_data, down_data))
I create a list of 6 random numbers between a minimum and a maximum.
I sort them from down to up in a list.
I sort them from up to down in another list.
I put the two lists together.
It's working, but I don't like how it looks. I'm sure there must be a better way to do this but I just can't find anything. Thank you for your help!
Is it intentional that both sides have the same numbers ? If not, you should generate random numbers for the full size and concatenate ascending and descending sorts of half the values on each side:
import numpy as np
min_value = 75
max_value = 100
size = 12
random_data = np.random.uniform(min_value, max_value, size)
left_side = np.sort(random_data[::2])
right_side = np.sort(random_data[1::2])[::-1]
df = np.concatenate((left_side,right_side))
output:
print(df)
[84.35962408 84.86455724 84.86643652 85.95444697 86.97411648 95.55028286
97.6394171 94.16644573 94.05654689 92.12869314 88.52363283 80.19109841]
You could also do it "in-place" directly in the resulting array:
df = np.random.uniform(min_value, max_value, size)
df[:size//2].sort()
df[size//2:][::-1].sort()
In normal Python (i.e. not using the numpy module), you can take a similar approach:
import random
values = [random.randrange(min_value,max_value) for _ in range(size)]
values[:size//2] = sorted(values[:size//2])
values[size//2:] = sorted(values[size//2:],reverse=True)
print(values)
# [78, 79, 80, 80, 87, 93, 98, 92, 90, 86, 85, 81]
Not sure if you need this, but, here is the idea I suggested in comments:
import math
import random
size = 20
dec = 3
mx = 113
mn = 67
domain = sorted([random.uniform(0, math.pi) for _ in range(size)])
use_this = [round(fctr * math.sin(x), dec) for x in domain]
mx_l = max(use_this)
mn_l = min(use_this)
fctr = (mx - mn)/(mx_l - mn_l)
use_this = [round((fctr * (x - mn_l)) + mn, 0) for x in use_this]
print(use_this)
Note:
sin() is monotonically increasing between 0 and pi/2 and decreasing between pi/2 and pi
Used the logic at this SO answer
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am working with q-tables and I got 30 * 30 * 30 * 30=810000 different states. I want a function that takes for example [10, 20, 16, 5] as input and this should correspond to a particular row representing this exact combination of state but I cannot figure out how to do that. One (bad) approach would be 10 * 20 * 15 * 5=15000 but then row number 15 000 would also be represented by 20 * 10 * 5 * 15 = 15000 and I do not want that. How can I make this work?
One way would be to represent your table as a 4-dimensional list:
self.q_table = [[[[0 for _ in range(30)] for _ in range(30)] for _ in range(30)] for _ in range(30)]
so you can do:
def func(self, coords):
[q, r, s, t] = coords
entry = self.q_table[q][r][s][t]
...
If you wanted to flatten it to a single-dimensional list, then you need to multiple each coordinate by an increasing power of 30 to make sure each combination of coordinates yields a unique result:
self.q_table = [0 for _ in range(30**4)]
def func(self, coords):
row_num = sum(i * 30**p for p, i in enumerate(coords))
entry = self.q_table[row_num]
...
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am new to python (24 hours old).
I am trying to create a program in python that can help me solve equations.
For example: To calculate profit, the general, and a very simple equation for a manufacturing unit should be:
Labor-hour-rate*(hours_worked) + No_of_units_produced*raw_material_cost = Total cost.
Now, in this equation there 5 variables. I want to create a program where I input 4 of the 5 variables, the 5th variable should be calculated.
For e.g., If I input
Labour-hour-rate = 20
hours_worked = 2
No_of_units_produced = 10
Total Cost = 80
then, the program should calculate, raw_material_cost = 4
I know one way is to create a separate function for each parameter, but I think there must be a smarter way to do it in Python
Can anyone help me with this?
Thanks
Himanshu
You can solve using namedtuple. And what you want to find set is as None.
import collections
def calculate(args):
if args.total_cost is None:
total_cost = (args.labour_hour_rate * args.hours_worked) + (args.no_of_units_produced * args.raw_material_cost)
print("total_cost =", total_cost)
elif args.hours_worked is None:
hours_worked = (args.total_cost - args.no_of_units_produced * args.raw_material_cost) / args.labour_hour_rate
print("hours_worked =", hours_worked)
elif args.labour_hour_rate is None:
labour_hour_rate = (args.total_cost - args.no_of_units_produced * args.raw_material_cost) / args.hours_worked
print("labour_hour_rate =", labour_hour_rate)
elif args.no_of_units_produced is None:
no_of_units_produced = (args.total_cost - args.labour_hour_rate * args.hours_worked) / args.raw_material_cost
print("no_of_units_produced =", no_of_units_produced)
elif args.raw_material_cost is None:
raw_material_cost = (args.total_cost - args.labour_hour_rate * args.hours_worked) / args.no_of_units_produced
print("raw_material_cost =", raw_material_cost)
Variables = collections.namedtuple("Equation", "labour_hour_rate hours_worked no_of_units_produced total_cost raw_material_cost")
calculate(Variables(20, 2, 10, 80, None))
calculate(Variables(20, 2, 10, None, 4))
calculate(Variables(20, 2, None, 80, 4))
calculate(Variables(20, None, 10, 80, 4))
calculate(Variables(None, 2, 10, 80, 4))
Output:
raw_material_cost = 4.0
total_cost = 80
no_of_units_produced = 10.0
hours_worked = 2.0
labour_hour_rate = 20.0
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to reproduce this [50 x 50] matrix generated with Python as:
n = 50
a = np.linspace(-5, 5, n).reshape(-1,1)
b = a
np.sum(a**2, 1).reshape(-1, 1) + np.sum(b**2, 1)
using R. The problem is that the result is some sort of matrix, which cannot be reproduced through:
n = 50
a = seq(-5, 5, length.out = n)
b = a
a^2 + b^2
which generates a vector.
I am not familiar with the object names in Python, but I see that np.sum(a**2, 1).reshape(-1, 1) produces what looks like a [50 x 1] column vector:
array([[ 2.50000000e+01],
[ 2.30008330e+01],
...
[ 2.10849646e+01],
[ 2.30008330e+01],
[ 2.50000000e+01]])
while np.sum(b**2, 1):
array([ 2.50000000e+01, 2.30008330e+01, 2.10849646e+01,
1.92523948e+01, 1.75031237e+01, 1.58371512e+01,
...
1.27551020e+01, 1.42544773e+01, 1.58371512e+01,
1.75031237e+01, 1.92523948e+01, 2.10849646e+01,
2.30008330e+01, 2.50000000e+01])
looks like the transposed of that same vector. So we have an operation of the form [50 x 1] * [1 x 50] = [50 x 50].
What is the generic name of this operation? And how can I reproduce it in R?
You are looking for ?outer I believe. As per the help file, it returns:
The outer product of the arrays X and Y ... the array A with dimension
c(dim(X), dim(Y))
So, for your specific example, try:
outer(a^2,b^2,FUN=`+`)
# [,1] [,2] [,3]
#[1,] 50.00000 48.00083 46.08496 ...to col 50
#[2,] 48.00083 46.00167 44.08580 ...to col 50
#[3,] 46.08496 44.08580 42.16993 ...to col 50
# ...to row 50