This question already has answers here:
Find highest and lowest number from the string of numbers
(5 answers)
Sorting numbers in python
(3 answers)
Closed 4 years ago.
I tried to use the max() function but I can't get the right max with it.
Example:
numbers = "4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
a = max(numbers.split(" "))
b = min(numbers.split(" "))
print a
print b
Output:
6
-214
It's obviously wrong, the max should be 542. Does anyone know why max() fails to find the correct max value? How to get the correct answer?
numbers.split(" ") gives you a list of strings, not integers.
If you want max() and min() to find the highest and lowest integers, then you need to convert your list of strings to a list of integers using map(int, your_array).
Example
numbers = "4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
numbers = numbers.split(" ") # Splits your string into a list of strings
numbers = map(int, numbers) # Converts each element in your list to int
a = max(numbers)
b = min(numbers)
print a # Outputs 542
print b # Outputs -214
In the other hand, you don't need to use map or other function to convert your string list to integer list, because it iterates over the list one more time, max function accepts key parameter, you can put a callable there, like this:
a = max(numbers.split(), key=int)
b = min(numbers.split(), key=int)
also in this case split() is same with split(" ").
Python max() function is accurate.
You should have a look at numbers.split(" ").
It returns a list of strings. Hence, the max compares and gives the max of the strings in the list.
>>> numbers.split(" ")
>>> ['4', '5', '29', '54', '4', '0', '-214', '542', '-64', '1', '-3', '6', '-6']
And, as string comparisons go, it will compare the first letter of each string, and the max would be: 6.
Because a and b are of type string, not an int.
numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
a = max(map(int, numbers.split(" ")))
b = min(map(int, numbers.split(" ")))
print a
print b
# 542
# -214
Try this:
numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
a = max(list(map(int, numbers.split(" "))))
b = min(list(map(int, numbers.split(" "))))
print a
print b
Related
I would like to ask a question please regarding printing the number of different numbers in python.
for example:
Let us say that I have the following list:
X = [5, 5, 5]
Since here we have only one number, I want to build a code that can recognize that we have only one number here so the output must be:
1
The number is: 5
Let us say that I have the following list:
X = [5,4,5]
Since here we have two numbers (5 and 4), I want to the code to recognize that we have only two numbers here so the output must be:
2
The numbers are: 4, 5
Let us say that I have the following list:
X = [24,24,24,24,24,24,24,24,26,26,26,26,26,26,26,26]
Since here we have two numbers (24 and 26), I want to the code to recognize that we have only two numbers here so the output must be:
2
The numbers are: 24, 26
You could keep track of unique numbers with a set object:
X = [1,2,3,3,3]
S = set(X)
n = len(S)
print(n, S) # 3 {1,2,3}
Bear in mind sets are unordered, so you would need to convert back to a list and sort them if needed.
you can change this list into set, it will remove duplicate, then you can change it again into list.
list(set(X))
You can try numpy.unique, and use len() on the result
May I ask you please if we can use set() to read the data in a specific column in pandas?
For example, I have the following the DataFrame:
df1= [ 0 -10 2 5
1 24 5 10
2 30 3 6
3 30 2 1
4 30 4 5 ]
where the first column is the index..
I tried first to isolate the second column
[-10
24
30
30
30]
using the following: x = pd.DataFrame(df1, coulmn=[0])
Then, I transposed the column using the following XX = x.T
Then, I used set() function.
However, instead of obtaining
[-10 24 30]
I got the following [0 1 2 3 4]
So set() read the index instead of reading the first column
I have tried many ways in doing this but it doesn't work for my case. Many of them are multiplied by columns, for my case is need to get the first two digit from a single column and multiply.
this is a column in a dataset and I need to get the first two-digit and multiply with each other
For example: for the first row I need to get 4 multiply by 5 and the result will store in a new column
May I know how to do it?
Thank you in advanced^^
For following dataframe
import pandas as pd
d={'locationID':[12,234,34]}
data=pd.DataFrame(data=d)
print(data)
locationID
0 12
1 234
2 34
If you want to multiply all the digits
function to multiply all the digits,
def multiplyall(number):
result=1
for i in range(len(str(number))):
result=int(str(number)[i])*result
return result
create column and add values according to the function in one line with insert(location, column name, column values)
data.insert(len(data.columns), 'new_column', data['locationID'].apply(lambda x: multiply_all(x)).tolist())
you'll get the following output
print(data)
locationID new_column
0 12 2
1 234 24
2 34 12
If you want to multiply ONLY 1st and 2nd digits
function to multiply 1st and 2nd digits,
def multiply_firstsecond(number):
result=number
if len(str(number))>1:
result=int(str(number)[0])* int(str(number)[1])
return result
Similarly,
data.insert(len(data.columns), 'new_column', data['locationID'].apply(lambda x: multiply_firstsecond(x)).tolist())
output for this one,
print(data)
locationID new_column
0 12 2
1 234 6
2 34 12
PLEASE make sure you have no NaN or non-numeric values in the column to avoid errors.
Like this:
ID = ['45.0',
'141.0',
'191.0',
'143.0',
'243.0']
N = [f"{int(s[0])*int(s[1])}" for s in ID]
print(N)
Output:
['20',
'4',
'9',
'4',
'8']
This should work
data = DataFrame([
(54423),
(2023),
(4353),
(76754)
], columns=["number_1"])
data["number_2"] = 0
def calculation(num):
mult = num
if len(str(num)) >= 2:
str_num = str(num)
mult = int(str_num[0]) * int(str_num[1])
return mult
data["number_2"] = data["number_1"].apply(calculation)
print(data)
number_1 number_2
0 54423 20
1 2023 0
2 4353 12
3 76754 42
I have a string of number chars that I want to change to type int, but I need to remove the parentheses and the numbers in it (it's just a multiplier for my application, this is how I get the data).
Here is the sample code.
import pandas as pd
voltages = ['0', '0', '0', '0', '0', '310.000 (31)', '300.000 (30)', '190.000 (19)', '0', '20.000 (2)']
df = pd.DataFrame(voltages, columns=['Voltage'])
df
Out [1]:
Voltage
0 0
1 0
2 0
3 0
4 0
5 310.000 (31)
6 300.000 (30)
7 190.000 (19)
8 0
9 20.000 (2)
How can I remove the substrings within the parenthesis? Is there a Pandas.series.str way to do it?
Use str.replace with regex:
df.Voltage.str.replace(r"\s\(.*","")
Out:
0 0
1 0
2 0
3 0
4 0
5 310.000
6 300.000
7 190.000
8 0
9 20.000
Name: Voltage, dtype: object
You can also use str.split()
df_2 = df['Voltage'].str.split(' ', 0, expand = True).rename(columns = {0:'Voltage'})
df_2['Voltage'] = df_2['Voltage'].astype('float')
If you know the separating character will always be a space then the following is quite a neat way of doing it:
voltages = [i.rsplit(' ')[0] for i in voltages]
I think you could try this:
new_series = df['Voltage'].apply(lambda x:int(x.split('.')[0]))
df['Voltage'] = new_series
I hope it helps.
Hopefully, this will work for you:
result = source_value[:source_value.find(" (")]
NOTE: the find function requires a string as source_value. But if you have parens in your value, I assume it is a string.
This is the programing i used:
import math
iq= (input("enter the price")).split()
fp=(input ("enter the price")).split()
for i in range(len(iq)):
for n in range(len(fp)):
print (int(iq[i])* int(fp[i]))
I want it to print:
multiply each 'iq' by the corresponding 'fp'
1
4
6
It prints:
multiply each 'iq' by each 'fp'
1
2
3
2
4
6
3
6
9
If I'm understanding correctly, both lists should have the same length right? If so, you can just use one for loop:
for i in range(len(iq)):
print (int(iq[i])* int(fp[i]))
Also, should the input be appended to a list instead of set equal to a variable?
How do i add all imputed numbers in a string?
Ex:
input:
5 5 3 5
output
18
and it must supports ('-')
Ex.
input
-5 5 3 5
output
8
I write something like this:
x = raw_input()
print sum(map(int,str(x)))
and it adds normally if x>0
But what to do with ('-') ?
I understand that i need to use split() but my knowledge is not enough (
You're close, you just need to split the string on spaces. Splitting will produce the list of strings ['-5', '5', '3', '5']. Then you can do the rest of the map and sum as you intended.
>>> s = '-5 5 3 5'
>>> sum(map(int, s.split()))
8
its simple
>>> input = raw_input('Enter your input: ')
Enter your input: 5 5 10 -10
>>> list_numbers = [int(item) for item in input.split(' ')]
>>> print list_numbers
[5, 5, 10, -10]
And after what you want :)
You can use the following line:
sum(map(int, raw_input().split()))