Reset в питоне это

Как сбросить индекс в Pandas DataFrame(с примерами)

Вы можете использовать следующий синтаксис для сброса индекса в pandas DataFrame:

df.reset_index(drop= True , inplace= True ) 

Обратите внимание на следующие аргументы:

  • drop : Указание True запрещает pandas сохранять исходный индекс в виде столбца в DataFrame.
  • inplace : Указание True позволяет pandas заменить индекс в исходном DataFrame вместо создания копии DataFrame.

В следующих примерах показано, как использовать этот синтаксис на практике.

Пример 1: сбросить индекс и удалить старый индекс

Предположим, у нас есть следующие Pandas DataFrame:

import pandas as pd #define DataFrame df = pd.DataFrame(, index=[0, 4, 3, 5, 2, 1, 7, 6]) #view DataFrame print(df) points assists rebounds 0 25 5 11 4 12 7 8 3 15 7 10 5 14 9 6 2 19 12 6 1 23 9 5 7 25 9 9 6 29 4 12 

В следующем коде показано, как сбросить индекс DataFrame и полностью удалить старый индекс:

#reset index df.reset_index(drop= True , inplace= True ) #view updated DataFrame print(df) points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12 

Обратите внимание, что индекс был сброшен, и значения в индексе теперь находятся в диапазоне от 0 до 7.

Пример 2: сбросить индекс и сохранить старый индекс как столбец

Предположим, у нас есть следующие Pandas DataFrame:

import pandas as pd #define DataFrame df = pd.DataFrame(, index=['A', 'C', 'D', 'B', 'E', 'G', 'F', 'H']) #view DataFrame print(df) points assists rebounds A 25 5 11 C 12 7 8 D 15 7 10 B 14 9 6 E 19 12 6 G 23 9 5 F 25 9 9 H 29 4 12 

В следующем коде показано, как сбросить индекс DataFrame и сохранить старый индекс в виде столбца в DataFrame:

#reset index and retain old index as a column df.reset_index(inplace= True ) #view updated DataFrame print(df) index points assists rebounds 0 A 25 5 11 1 C 12 7 8 2 D 15 7 10 3 B 14 9 6 4 E 19 12 6 5 G 23 9 5 6 F 25 9 9 7 H 29 4 12 

Обратите внимание, что индекс был сброшен, и значения в индексе теперь находятся в диапазоне от 0 до 7.

Также обратите внимание, что старый индекс (с буквами) сохраняется как новый столбец в DataFrame под названием «индекс».

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные операции в pandas:

Источник

turtle — Turtle graphics¶

Turtle graphics is an implementation of the popular geometric drawing tools introduced in Logo, developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.

Turtle can draw intricate shapes using programs that repeat simple moves.

../_images/turtle-star.png

In Python, turtle graphics provides a representation of a physical “turtle” (a little robot with a pen) that draws on a sheet of paper on the floor.

It’s an effective and well-proven way for learners to encounter programming concepts and interaction with software, as it provides instant, visible feedback. It also provides convenient access to graphical output in general.

Turtle drawing was originally created as an educational tool, to be used by teachers in the classroom. For the programmer who needs to produce some graphical output it can be a way to do that without the overhead of introducing more complex or external libraries into their work.

Читайте также:  Читать строку до символа java

Tutorial¶

New users should start here. In this tutorial we’ll explore some of the basics of turtle drawing.

Starting a turtle environment¶

In a Python shell, import all the objects of the turtle module:

If you run into a No module named ‘_tkinter’ error, you’ll have to install the Tk interface package on your system.

Basic drawing¶

Send the turtle forward 100 steps:

You should see (most likely, in a new window on your display) a line drawn by the turtle, heading East. Change the direction of the turtle, so that it turns 120 degrees left (anti-clockwise):

Let’s continue by drawing a triangle:

forward(100) left(120) forward(100) 

Notice how the turtle, represented by an arrow, points in different directions as you steer it.

Experiment with those commands, and also with backward() and right() .

Pen control¶

Try changing the color — for example, color(‘blue’) — and width of the line — for example, width(3) — and then drawing again.

You can also move the turtle around without drawing, by lifting up the pen: up() before moving. To start drawing again, use down() .

The turtle’s position¶

Send your turtle back to its starting-point (useful if it has disappeared off-screen):

The home position is at the center of the turtle’s screen. If you ever need to know them, get the turtle’s x-y co-ordinates with:

And after a while, it will probably help to clear the window so we can start anew:

Making algorithmic patterns¶

Using loops, it’s possible to build up geometric patterns:

for steps in range(100): for c in ('blue', 'red', 'green'): color(c) forward(steps) right(30) 

— which of course, are limited only by the imagination!

Let’s draw the star shape at the top of this page. We want red lines, filled in with yellow:

Just as up() and down() determine whether lines will be drawn, filling can be turned on and off:

while True: forward(200) left(170) if abs(pos())  1: break 

Finally, complete the filling:

(Note that filling only actually takes place when you give the end_fill() command.)

How to…¶

This section covers some typical turtle use-cases and approaches.

Get started as quickly as possible¶

One of the joys of turtle graphics is the immediate, visual feedback that’s available from simple commands — it’s an excellent way to introduce children to programming ideas, with a minimum of overhead (not just children, of course).

The turtle module makes this possible by exposing all its basic functionality as functions, available with from turtle import * . The turtle graphics tutorial covers this approach.

It’s worth noting that many of the turtle commands also have even more terse equivalents, such as fd() for forward() . These are especially useful when working with learners for whom typing is not a skill.

You’ll need to have the Tk interface package installed on your system for turtle graphics to work. Be warned that this is not always straightforward, so check this in advance if you’re planning to use turtle graphics with a learner.

Use the turtle module namespace¶

Using from turtle import * is convenient — but be warned that it imports a rather large collection of objects, and if you’re doing anything but turtle graphics you run the risk of a name conflict (this becomes even more an issue if you’re using turtle graphics in a script where other modules might be imported).

The solution is to use import turtle — fd() becomes turtle.fd() , width() becomes turtle.width() and so on. (If typing “turtle” over and over again becomes tedious, use for example import turtle as t instead.)

Use turtle graphics in a script¶

It’s recommended to use the turtle module namespace as described immediately above, for example:

import turtle as t from random import random for i in range(100): steps = int(random() * 100) angle = int(random() * 360) t.right(angle) t.fd(steps) 

Another step is also required though — as soon as the script ends, Python will also close the turtle’s window. Add:

to the end of the script. The script will now wait to be dismissed and will not exit until it is terminated, for example by closing the turtle graphics window.

Use object-oriented turtle graphics¶

Other than for very basic introductory purposes, or for trying things out as quickly as possible, it’s more usual and much more powerful to use the object-oriented approach to turtle graphics. For example, this allows multiple turtles on screen at once.

In this approach, the various turtle commands are methods of objects (mostly of Turtle objects). You can use the object-oriented approach in the shell, but it would be more typical in a Python script.

The example above then becomes:

from turtle import Turtle from random import random t = Turtle() for i in range(100): steps = int(random() * 100) angle = int(random() * 360) t.right(angle) t.fd(steps) t.screen.mainloop() 

Note the last line. t.screen is an instance of the Screen that a Turtle instance exists on; it’s created automatically along with the turtle.

The turtle’s screen can be customised, for example:

t.screen.title('Object-oriented turtle demo') t.screen.bgcolor("orange") 

Explanation¶

The turtle module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5.

It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch.

The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.

The object-oriented interface uses essentially two+two classes:

  1. The TurtleScreen class defines graphics windows as a playground for the drawing turtles. Its constructor needs a tkinter.Canvas or a ScrolledCanvas as argument. It should be used when turtle is used as part of some application. The function Screen() returns a singleton object of a TurtleScreen subclass. This function should be used when turtle is used as a standalone tool for doing graphics. As a singleton object, inheriting from its class is not possible. All methods of TurtleScreen/Screen also exist as functions, i.e. as part of the procedure-oriented interface.
  2. RawTurtle (alias: RawPen ) defines Turtle objects which draw on a TurtleScreen . Its constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle objects know where to draw. Derived from RawTurtle is the subclass Turtle (alias: Pen ), which draws on “the” Screen instance which is automatically created, if not already present. All methods of RawTurtle/Turtle also exist as functions, i.e. part of the procedure-oriented interface.

The procedural interface provides functions which are derived from the methods of the classes Screen and Turtle . They have the same names as the corresponding methods. A screen object is automatically created whenever a function derived from a Screen method is called. An (unnamed) turtle object is automatically created whenever any of the functions derived from a Turtle method is called.

To use multiple turtles on a screen one has to use the object-oriented interface.

In the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here.

Источник

Pandas DataFrame reset_index(): сброс индексов

Pandas DataFrame reset_index() используется для сброса индекса DataFrame. Функция reset_index() используется для установки списка целых чисел от 0 до длины данных в качестве индекса.

Метод reset_index() полезен, когда индекс необходимо рассматривать как столбец или когда индекс не имеет смысла и его необходимо сбросить до значения по умолчанию перед другой операцией. В случае MultiIndex метод reset_index() может использоваться для удаления одного или нескольких уровней. Он либо сбрасывает индекс, либо его уровень. Давайте начнем с нескольких основных.

DataFrame в Pandas

DataFrame — это не что иное, как представление листа Excel в памяти с помощью языка программирования Python. Объект index представляет собой неизменяемый массив. Индексация позволяет нам получить доступ к строке или столбцу с помощью метки. Pandas DataFrame — это композиция, содержащая двумерные данные и связанные с ними метки.

DataFrames широко используются в науке о данных, машинном обучении, научных вычислениях и многих других областях, связанных с интенсивным использованием данных.

Существует множество способов создать Pandas DataFrame. В большинстве случаев вы будете использовать конструктор DataFrame и заполнять данные, метки и другую информацию. Иногда вы будете импортировать данные из файла CSV или Excel, можете передать данные в виде двумерного списка, кортежа или массива NumPy. Вы также можете передать его как экземпляр словаря или Pandas Series или как один из многих других типов данных, не рассматриваемых в этом примере.

Прежде чем продолжить, давайте разберемся с set_index() в Pandas.

Что такое функция DataFrame set_index() в Pandas?

Pandas DataFrame set_index() — это функция, которая используется для установки списка, серии или фрейма данных в качестве индекса фрейма данных. Pandas DataFrame — это двухмерная структура данных с метками, столбцы которой потенциально могут быть другого типа.

Источник

Оцените статью