Что значит процент в информатике в пайтоне
Перейти к содержимому

Что значит процент в информатике в пайтоне

  • автор:

Как рассчитать процентили в Python (с примерами)

N -й процентиль набора данных — это значение, которое отсекает первые n процентов значений данных, когда все значения отсортированы от наименьшего к наибольшему.

Например, 90-й процентиль набора данных — это значение, которое отсекает нижние 90 % значений данных от верхних 10 % значений данных.

Мы можем быстро вычислить процентили в Python, используя функцию numpy.percentile() , которая использует следующий синтаксис:

numpy.percentile (а, д)

  • а: Массив значений
  • q: Процентили или последовательность процентилей для вычисления, которые должны быть в диапазоне от 0 до 100 включительно.

В этом руководстве объясняется, как использовать эту функцию для расчета процентилей в Python.

Как найти процентили массива

Следующий код иллюстрирует, как найти различные процентили для заданного массива в Python:

Как найти процентили столбца DataFrame

В следующем коде показано, как найти значение 95-го процентиля для одного столбца pandas DataFrame:

Как найти процентили нескольких столбцов DataFrame

В следующем коде показано, как найти значение 95-го процентиля для нескольких столбцов в кадре данных pandas:

Обратите внимание, что мы смогли использовать функцию pandas quantile() в приведенных выше примерах для вычисления процентилей.

What is the result of % in Python?

What does the % in a calculation? I can’t seem to work out what it does.

Does it work out a percent of the calculation for example: 4 % 2 is apparently equal to 0. How?

orange's user avatar

20 Answers 20

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

Example 1: 6%2 evaluates to 0 because there’s no remainder if 6 is divided by 2 ( 3 times ).

Example 2: 7%2 evaluates to 1 because there’s a remainder of 1 when 7 is divided by 2 ( 3 times ).

So to summarise that, it returns the remainder of a division operation, or 0 if there is no remainder. So 6%2 means find the remainder of 6 divided by 2.

meder omuraliev's user avatar

Somewhat off topic, the % is also used in string formatting operations like %= to substitute values into a string:

Again, off topic, but it seems to be a little documented feature which took me awhile to track down, and I thought it was related to Pythons modulo calculation for which this SO page ranks highly.

An expression like x % y evaluates to the remainder of x ÷ y — well, technically it is "modulus" instead of "reminder" so results may be different if you are comparing with other languages where % is the remainder operator. There are some subtle differences (if you are interested in the practical consequences see also "Why Python’s Integer Division Floors" bellow).

Precedence is the same as operators / (division) and * (multiplication).

  • 9 divided by 2 is equal to 4.
  • 4 times 2 is 8
  • 9 minus 8 is 1 — the remainder.

Python gotcha: depending on the Python version you are using, % is also the (deprecated) string interpolation operator, so watch out if you are coming from a language with automatic type casting (like PHP or JS) where an expression like ’12’ % 2 + 3 is legal: in Python it will result in TypeError: not all arguments converted during string formatting which probably will be pretty confusing for you.

[update for Python 3]

User n00p comments:

9/2 is 4.5 in python. You have to do integer division like so: 9//2 if you want python to tell you how many whole objects is left after division(4).

To be precise, integer division used to be the default in Python 2 (mind you, this answer is older than my boy who is already in school and at the time 2.x were mainstream):

In modern Python 9 / 2 results 4.5 indeed:

[update]

User dahiya_boy asked in the comment session:

Q. Can you please explain why -11 % 5 = 4 — dahiya_boy

This is weird, right? If you try this in JavaScript:

This is because in JavaScript % is the "remainder" operator while in Python it is the "modulus" (clock math) operator.

In Java and iOS -11 % 5 = -1 whereas in python and ruby -11 % 5 = 4 .

Well half of the reason is explained by the Paulo Scardine, and rest of the explanation is below here

In Java and iOS, % gives the remainder that means if you divide 11 % 5 gives Quotient = 2 and remainder = 1 and -11 % 5 gives Quotient = -2 and remainder = -1 .

Sample code in swift iOS.

enter image description here

But when we talk about in python its gives clock modulus. And its work with below formula

mod(-11,5) = -11 — 5 * Floor(-11/5) => -11 —

Sample code in python 3.0.

enter image description here

Why Python’s Integer Division Floors

I was asked (again) today to explain why integer division in Python returns the floor of the result instead of truncating towards zero like C.

For positive numbers, there’s no surprise:

But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):

This disturbs some people, but there is a good mathematical reason. The integer division operation (//) and its sibling, the modulo operation (%), go together and satisfy a nice mathematical relationship (all variables are integers):

(assuming a and b are >= 0).

If you want the relationship to extend for negative a (keeping b positive), you have two choices: if you truncate q towards zero, r will become negative, so that the invariant changes to 0 <= abs(r) < otherwise, you can floor q towards negative infinity, and the invariant remains 0 <= r < b. [update: fixed this para]

In mathematical number theory, mathematicians always prefer the latter choice (see e.g. Wikipedia). For Python, I made the same choice because there are some interesting applications of the modulo operation where the sign of a is uninteresting. Consider taking a POSIX timestamp (seconds since the start of 1970) and turning it into the time of day. Since there are 24*3600 = 86400 seconds in a day, this calculation is simply t % 86400. But if we were to express times before 1970 using negative numbers, the "truncate towards zero" rule would give a meaningless result! Using the floor rule it all works out fine.

Other applications I’ve thought of are computations of pixel positions in computer graphics. I’m sure there are more.

For negative b, by the way, everything just flips, and the invariant becomes:

So why doesn’t C do it this way? Probably the hardware didn’t do this at the time C was designed. And the hardware probably didn’t do it this way because in the oldest hardware, negative numbers were represented as "sign + magnitude" rather than the two’s complement representation used these days (at least for integers). My first computer was a Control Data mainframe and it used one’s complement for integers as well as floats. A pattern of 60 ones meant negative zero!

Tim Peters, who knows where all Python’s floating point skeletons are buried, has expressed some worry about my desire to extend these rules to floating point modulo. He’s probably right; the truncate-towards-negative-infinity rule can cause precision loss for x%1.0 when x is a very small negative number. But that’s not enough for me to break integer modulo, and // is tightly coupled to that.

PS. Note that I am using // instead of / — this is Python 3 syntax, and also allowed in Python 2 to emphasize that you know you are invoking integer division. The / operator in Python 2 is ambiguous, since it returns a different result for two integer operands than for an int and a float or two floats. But that’s a totally separate story; see PEP 238.

Posted by Guido van Rossum at 9:49 AM

Django Fan

Форматирование строк или "Что означает %s в python?"

Форматирование строк или "Что означает %s в python?"

  • Опубликовано:
  • Теги: python

Недавно узнал, что блог время от времени находят по запросу «что означает %s в python». Вспоминаю себя – когда я начинал изучать Python, мне хотелось быстрых и понятных ответов (мол, «не морочь голову, пальцем покажи»). Для таких нетерпеливых эта статья.

Для начала несколько примеров

Теперь вкратце как работает оператор %

Выражение форматирования можно условно разделить на три части:

Обозначения %s, %d, %g и т. п. — это форматы типов данных. Если вы знакомы с языком Си, то это тот же синтаксис, что используется для вывода на печать printf() .

Спецификации различных типов данных Python приведены в следующей таблице:

Формат Значение
‘d’ Целое десятичное число.
‘i’ Целое десятичное число.
‘o’ Восьмеричное число.
‘u’ Устаревший тип – то же что ‘d’ .
‘x’ Шестнадцатеричное число (нижний регистр).
‘X’ Шестнадцатеричное число (верхний регистр).
‘e’ Вещественное число в экспоненциальном виде (нижний регистр).
‘E’ Вещественное число в экспоненциальном виде (верхний регистр).
‘f’ Вещественное число в десятичном виде.
‘F’ Вещественное число в десятичном виде.
‘g’ Вещественное число. Использует формат ‘f’ или ‘e’ в нижнем регистре.
‘G’ Вещественное число. Использует формат ‘F’ или ‘E’ в верхнем регистре.
‘c’ Один символ (или цифра).
‘r’ Строка, в которую любой объект Python конвертируется с помощью repr().
‘s’ Строка, в которую любой объект Python конвертируется с помощью str().
‘%’ Аргумент не конвертируется, выводится просто символ ‘%’ .

Встроенная функция format()

В строке «поля для замены» заключаются в фигурные скобки <> . Все, что не заключено в скобки, воспринимается как обычный текст, которые копируется в неизменном виде. Чтобы передать в тексте символы фигурных скобок, их дублируют: << и >> .
Поля для замены форматируются следующим образом:

где
Записывается так:

Как видите, этот способ гораздо гибче оператора ‘%’, так как одни и те же значения мы можем использовать повторно и в любом порядке. Также можно передать именованные аргументы, и тогда обращаться к ним будем не по номерам, а по именам.

Как вычислить процент в Python

Чтобы вычислить процент в Python, вы можете использовать оператор деления(/), чтобы получить частное из двух чисел, а затем умножить это частное на 100, используя оператор умножения(*), чтобы получить процент.

Вы можете создать пользовательскую функцию в Python для расчета процентов.

Вы можете добавить оператор if, если целое равно 0, вернуть 0, иначе это вызовет исключение.

Если вам нужно процентное отношение двух чисел, нужно использовать следующий код.

Знак % в Python (оператор по модулю)

Знак процента в Python называется оператором по модулю «%», который возвращает остаток после деления левого операнда на правый операнд.

Результат будет отображаться как «1». Здесь оператор по модулю «%» возвращает остаток после деления двух чисел.

Оператор %s позволяет добавлять значение к строке. %s означает, что вы хотите добавить к строке строковое значение; он также используется для форматирования чисел в строке.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *