This will find collisions between all the Sprites in two groups. Collision is determined by comparing the Sprite.rect attribute of each Sprite or by using the collided function if it is not None.
Every Sprite inside group1 is added to the return dictionary. The value for each item is the list of Sprites in group2 that intersect.
If either dokill argument is True, the colliding Sprites will be removed from their respective Group.
The collided argument is a callback function used to calculate if two sprites are colliding. It should take two sprites as values and return a bool value indicating if they are colliding. If collided is not passed, then all sprites must have a "rect" value, which is a rectangle of the sprite area, which will be used to calculate the collision.


The GroupSingle container only holds a single Sprite. When a new Sprite is added, the old one is removed.
There is a special property, GroupSingle.sprite, that accesses the Sprite that this Group contains. It can be None when the Group is empty. The property can also be assigned to add a Sprite into the GroupSingle container.


This group requires pygame.sprite.DirtySprite or any sprite that has the following attributes:
It uses the dirty flag technique and is therefore faster than the pygame.sprite.RenderUpdates if you have many static sprites. It also switches automatically between dirty rect update and full screen drawing, so you do no have to worry what would be faster.
Same as for the pygame.sprite.Group. You can specify some additional attributes through kwargs:
New in pygame 1.8.
You can pass the background too. If a background is already set, then the bgd argument has no effect.
screen_rect is in screen coordinates.
sprite must have been added to the renderer. It is not checked.
Default is 1000./80 where 80 is the fps I want to switch to full screen mode. This method's name is a typo and should be fixed.


sprite must have been added to the renderer. It is not checked.


You can pass the background too. If a background is already set, then the bgd argument has no effect.


Default is 1000./80 where 80 is the fps I want to switch to full screen mode. This method's name is a typo and should be fixed.


This group is fully compatible with pygame.sprite.Sprite.
You can set the default layer through kwargs using 'default_layer' and an integer for the layer. The default layer is 0.
If the sprite you add has an attribute _layer then that layer will be used. If the **kwarg contains 'layer' then the sprites passed will be added to that layer (overriding the sprite.layer attribute). If neither sprite has attribute layer nor **kwarg then the default layer is used to add the sprites.
New in pygame 1.8.
If the sprite(s) have an attribute layer then that is used for the layer. If **kwargs contains 'layer' then the sprite(s) will be added to that argument (overriding the sprite layer attribute). If neither is passed then the sprite(s) will be added to the default layer.
Bottom sprites first, top last.
Raises IndexOutOfBounds if the idx is not within range.
sprite must have been added to the renderer. It is not checked.
If the sprite is not found then it will return the default layer.
Brings the sprite to front, changing sprite layer to topmost layer (added at the end of that layer).
Moves the sprite to the bottom layer, moving it behind all other layers and adding one additional layer.
Returns all sprites from a layer, ordered by how they where added. It uses linear search and the sprites are not removed from layer.
The layers number must exist, it is not checked.


If the sprite(s) have an attribute layer then that is used for the layer. If **kwargs contains 'layer' then the sprite(s) will be added to that argument (overriding the sprite layer attribute). If neither is passed then the sprite(s) will be added to the default layer.


If the sprite is not found then it will return the default layer.


Raises IndexOutOfBounds if the idx is not within range.


Returns all sprites from a layer, ordered by how they where added. It uses linear search and the sprites are not removed from layer.


Moves the sprite to the bottom layer, moving it behind all other layers and adding one additional layer.


Brings the sprite to front, changing sprite layer to topmost layer (added at the end of that layer).


The layers number must exist, it is not checked.


This class derives from pygame.sprite.RenderUpdates(). It maintains the order in which the Sprites were added to the Group for rendering. This makes adding and removing Sprites from the Group a little slower than regular Groups.


This class is an alias to pygame.sprite.Group(). It has no additional functionality.


This class is derived from pygame.sprite.Group(). It has an extended draw() method that tracks the changed areas of the screen.
Draws all the Sprites to the surface, the same as Group.draw(). This method also returns a list of Rectangular areas on the screen that have been changed. The returned changes include areas of the screen that have been affected by previous Group.clear() calls.
The returned Rect list should be passed to pygame.display.update(). This will help performance on software driven display modes. This type of updating is usually only helpful on destinations with non-animating backgrounds.


Draws all the Sprites to the surface, the same as Group.draw(). This method also returns a list of Rectangular areas on the screen that have been changed. The returned changes include areas of the screen that have been affected by previous Group.clear() calls.
The returned Rect list should be passed to pygame.display.update(). This will help performance on software driven display modes. This type of updating is usually only helpful on destinations with non-animating backgrounds.


The base class for visible game objects. Derived classes will want to override the Sprite.update() and assign a Sprite.image and Sprite.rect attributes. The initializer can accept any number of Group instances to be added to.
When subclassing the Sprite, be sure to call the base initializer before adding the Sprite to Groups. For example:
The default implementation of this method does nothing; it's just a convenient "hook" that you can override. This method is called by Group.update() with whatever arguments you give it.
There is no need to use this method if not using the convenience method by the same name in the Group class.
Any number of Group instances can be passed as arguments. The Sprite will be added to the Groups it is not already a member of.
Any number of Group instances can be passed as arguments. The Sprite will be removed from the Groups it is currently a member of.
The Sprite is removed from all the Groups that contain it. This won't change anything about the state of the Sprite. It is possible to continue to use the Sprite after this method has been called, including adding it to Groups.
Returns True when the Sprite belongs to one or more Groups.
Return a list of all the Groups that contain this Sprite.


Any number of Group instances can be passed as arguments. The Sprite will be added to the Groups it is not already a member of.


Returns True when the Sprite belongs to one or more Groups.


Return a list of all the Groups that contain this Sprite.


The Sprite is removed from all the Groups that contain it. This won't change anything about the state of the Sprite. It is possible to continue to use the Sprite after this method has been called, including adding it to Groups.


Any number of Group instances can be passed as arguments. The Sprite will be removed from the Groups it is currently a member of.


The default implementation of this method does nothing; it's just a convenient "hook" that you can override. This method is called by Group.update() with whatever arguments you give it.
There is no need to use this method if not using the convenience method by the same name in the Group class.


Return a list containing all Sprites in a Group that intersect with another Sprite. Intersection is determined by comparing the Sprite.rect attribute of each Sprite.
The dokill argument is a bool. If set to True, all Sprites that collide will be removed from the Group.
The collided argument is a callback function used to calculate if two sprites are colliding. it should take two sprites as values, and return a bool value indicating if they are colliding. If collided is not passed, all sprites must have a "rect" value, which is a rectangle of the sprite area, which will be used to calculate the collision.
collided callables:
Example:


If the sprite collides with any single sprite in the group, a single sprite from the group is returned. On no collision None is returned.
If you don't need all the features of the pygame.sprite.spritecollide() function, this function will be a bit quicker.
The collided argument is a callback function used to calculate if two sprites are colliding. It should take two sprites as values and return a bool value indicating if they are colliding. If collided is not passed, then all sprites must have a "rect" value, which is a rectangle of the sprite area, which will be used to calculate the collision.


A pygame Surface is used to represent any image. The Surface has a fixed resolution and pixel format. Surfaces with 8-bit pixels use a color palette to map to 24-bit color.
Call pygame.Surface() to create a new image object. The Surface will be cleared to all black. The only required arguments are the sizes. With no additional arguments, the Surface will be created in a format that best matches the display Surface.
The pixel format can be controlled by passing the bit depth or an existing Surface. The flags argument is a bitmask of additional features for the surface. You can pass any combination of these flags:
Both flags are only a request, and may not be possible for all displays and formats.
Advance users can combine a set of bitmasks with a depth value. The masks are a set of 4 integers representing which bits in a pixel will represent each color. Normal Surfaces should not require the masks argument.
Surfaces can have many extra attributes like alpha planes, colorkeys, source rectangle clipping. These functions mainly effect how the Surface is blitted to other Surfaces. The blit routines will attempt to use hardware acceleration when possible, otherwise they will use highly optimized software blitting methods.
There are three types of transparency supported in pygame: colorkeys, surface alphas, and pixel alphas. Surface alphas can be mixed with colorkeys, but an image with per pixel alphas cannot use the other modes. Colorkey transparency makes a single color value transparent. Any pixels matching the colorkey will not be drawn. The surface alpha value is a single value that changes the transparency for the entire image. A surface alpha of 255 is opaque, and a value of 0 is completely transparent.
Per pixel alphas are different because they store a transparency value for every pixel. This allows for the most precise transparency effects, but it also the slowest. Per pixel alphas cannot be mixed with surface alpha and colorkeys.
There is support for pixel access for the Surfaces. Pixel access on hardware surfaces is slow and not recommended. Pixels can be accessed using the get_at() and set_at() functions. These methods are fine for simple access, but will be considerably slow when doing of pixel work with them. If you plan on doing a lot of pixel level work, it is recommended to use a pygame.PixelArray, which gives an array like view of the surface. For involved mathematical manipulations try the pygame.surfarray module (It's quite quick, but requires NumPy.)
Any functions that directly access a surface's pixel data will need that surface to be lock()'ed. These functions can lock() and unlock() the surfaces themselves without assistance. But, if a function will be called many times, there will be a lot of overhead for multiple locking and unlocking of the surface. It is best to lock the surface manually before making the function call many times, and then unlocking when you are finished. All functions that need a locked surface will say so in their docs. Remember to leave the Surface locked only while necessary.
Surface pixels are stored internally as a single number that has all the colors encoded into it. Use the map_rgb() and unmap_rgb() to convert between individual red, green, and blue values into a packed integer for that Surface.
Surfaces can also reference sections of other Surfaces. These are created with the subsurface() method. Any change to either Surface will effect the other.
Each Surface contains a clipping area. By default the clip area covers the entire Surface. If it is changed, all drawing operations will only effect the smaller area.
Draws a source Surface onto this Surface. The draw can be positioned with the dest argument. The dest argument can either be a pair of coordinates representing the position of the upper left corner of the blit or a Rect, where the upper left corner of the rectangle will be used as the position for the blit. The size of the destination rectangle does not effect the blit.
An optional area rectangle can be passed as well. This represents a smaller portion of the source Surface to draw.
New in pygame 1.8: Optional special_flags: BLEND_ADD, BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX.
New in pygame 1.8.1: Optional special_flags: BLEND_RGBA_ADD, BLEND_RGBA_SUB, BLEND_RGBA_MULT, BLEND_RGBA_MIN, BLEND_RGBA_MAX BLEND_RGB_ADD, BLEND_RGB_SUB, BLEND_RGB_MULT, BLEND_RGB_MIN, BLEND_RGB_MAX.
New in pygame 1.9.2: Optional special_flags: BLEND_PREMULTIPLIED
New in pygame 2.0.0: Optional special_flags: BLEND_ALPHA_SDL2 - Uses the SDL2 blitter for alpha blending, this gives different results than the default blitter, which is modelled after SDL1, due to different approximations used for the alpha blending formula. The SDL2 blitter also supports RLE on alpha blended surfaces which the pygame one does not.
The return rectangle is the area of the affected pixels, excluding any pixels outside the destination Surface, or outside the clipping area.
Pixel alphas will be ignored when blitting to an 8 bit Surface.
For a surface with colorkey or blanket alpha, a blit to self may give slightly different colors than a non self-blit.
Draws many surfaces onto this Surface. It takes a sequence as input, with each of the elements corresponding to the ones of blit(). It needs at minimum a sequence of (source, dest).
a list of rects of the areas changed if doreturn is True, otherwise None
list or None
New in pygame 1.9.4.
Creates a new copy of the Surface with the pixel format changed. The new pixel format can be determined from another existing Surface. Otherwise depth, flags, and masks arguments can be used, similar to the pygame.Surface() call.
If no arguments are passed the new Surface will have the same pixel format as the display Surface. This is always the fastest format for blitting. It is a good idea to convert all Surfaces before they are blitted many times.
The converted Surface will have no pixel alphas. They will be stripped if the original had them. See convert_alpha() for preserving or creating per-pixel alphas.
The new copy will have the same class as the copied surface. This lets as Surface subclass inherit this method without the need to override, unless subclass specific instance attributes also need copying.
Creates a new copy of the surface with the desired pixel format. The new surface will be in a format suited for quick blitting to the given format with per pixel alpha. If no surface is given, the new surface will be optimized for blitting to the current display.
Unlike the convert() method, the pixel format for the new image will not be exactly the same as the requested source, but it will be optimized for fast alpha blitting to the destination.
As with convert() the returned surface has the same class as the converted surface.
Makes a duplicate copy of a Surface. The new surface will have the same pixel formats, color palettes, transparency settings, and class as the original. If a Surface subclass also needs to copy any instance specific attributes then it should override copy().
Fill the Surface with a solid color. If no rect argument is given the entire Surface will be filled. The rect argument will limit the fill to a specific area. The fill will also be contained by the Surface clip area.
The color argument can be either a RGB sequence, a RGBA sequence or a mapped color index. If using RGBA, the Alpha (A part of RGBA) is ignored unless the surface uses per pixel alpha (Surface has the SRCALPHA flag).
New in pygame 1.8: Optional special_flags: BLEND_ADD, BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX.
New in pygame 1.8.1: Optional special_flags: BLEND_RGBA_ADD, BLEND_RGBA_SUB, BLEND_RGBA_MULT, BLEND_RGBA_MIN, BLEND_RGBA_MAX BLEND_RGB_ADD, BLEND_RGB_SUB, BLEND_RGB_MULT, BLEND_RGB_MIN, BLEND_RGB_MAX.
This will return the affected Surface area.
Move the image by dx pixels right and dy pixels down. dx and dy may be negative for left and up scrolls respectively. Areas of the surface that are not overwritten retain their original pixel values. Scrolling is contained by the Surface clip area. It is safe to have dx and dy values that exceed the surface size.
New in pygame 1.9.
Set the current color key for the Surface. When blitting this Surface onto a destination, any pixels that have the same color as the colorkey will be transparent. The color can be an RGB color or a mapped color integer. If None is passed, the colorkey will be unset.
The colorkey will be ignored if the Surface is formatted to use per pixel alpha values. The colorkey can be mixed with the full Surface alpha value.
The optional flags argument can be set to pygame.RLEACCEL to provide better performance on non accelerated displays. An RLEACCEL Surface will be slower to modify, but quicker to blit as a source.
Return the current colorkey value for the Surface. If the colorkey is not set then None is returned.
Set the current alpha value for the Surface. When blitting this Surface onto a destination, the pixels will be drawn slightly transparent. The alpha value is an integer from 0 to 255, 0 is fully transparent and 255 is fully opaque. If None is passed for the alpha value, then alpha blending will be disabled, including per-pixel alpha.
This value is different than the per pixel Surface alpha. For a surface with per pixel alpha, blanket alpha is ignored and None is returned.
Changed in pygame 2.0: per-surface alpha can be combined with per-pixel alpha.
The optional flags argument can be set to pygame.RLEACCEL to provide better performance on non accelerated displays. An RLEACCEL Surface will be slower to modify, but quicker to blit as a source.
Return the current alpha value for the Surface.
Lock the pixel data of a Surface for access. On accelerated Surfaces, the pixel data may be stored in volatile video memory or nonlinear compressed forms. When a Surface is locked the pixel memory becomes available to access by regular software. Code that reads or writes pixel values will need the Surface to be locked.
Surfaces should not remain locked for more than necessary. A locked Surface can often not be displayed or managed by pygame.
Not all Surfaces require locking. The mustlock() method can determine if it is actually required. There is no performance penalty for locking and unlocking a Surface that does not need it.
All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.
It is safe to nest locking and unlocking calls. The surface will only be unlocked after the final lock is released.
Unlock the Surface pixel data after it has been locked. The unlocked Surface can once again be drawn and managed by pygame. See the lock() documentation for more details.
All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.
It is safe to nest locking and unlocking calls. The surface will only be unlocked after the final lock is released.
Returns True if the Surface is required to be locked to access pixel data. Usually pure software Surfaces do not require locking. This method is rarely needed, since it is safe and quickest to just lock all Surfaces as needed.
All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.
Returns True when the Surface is locked. It doesn't matter how many times the Surface is locked.
Returns the currently existing locks for the Surface.
Return a copy of the RGBA Color value at the given pixel. If the Surface has no per pixel alpha, then the alpha value will always be 255 (opaque). If the pixel position is outside the area of the Surface an IndexError exception will be raised.
Getting and setting pixels one at a time is generally too slow to be used in a game or realtime situation. It is better to use methods which operate on many pixels at a time like with the blit, fill and draw methods - or by using pygame.surfarray/pygame.PixelArray.
This function will temporarily lock and unlock the Surface as needed.
New in pygame 1.9: Returning a Color instead of tuple. Use tuple(surf.get_at((x,y))) if you want a tuple, and not a Color. This should only matter if you want to use the color as a key in a dict.
Set the RGBA or mapped integer color value for a single pixel. If the Surface does not have per pixel alphas, the alpha value is ignored. Setting pixels outside the Surface area or outside the Surface clipping will have no effect.
Getting and setting pixels one at a time is generally too slow to be used in a game or realtime situation.
This function will temporarily lock and unlock the Surface as needed.
Return the integer value of the given pixel. If the pixel position is outside the area of the Surface an IndexError exception will be raised.
This method is intended for pygame unit testing. It unlikely has any use in an application.
This function will temporarily lock and unlock the Surface as needed.
New in pygame 1.9.2.
Return a list of up to 256 color elements that represent the indexed colors used in an 8-bit Surface. The returned list is a copy of the palette, and changes will have no effect on the Surface.
Returning a list of Color(with length 3) instances instead of tuples.
New in pygame 1.9.
Returns the red, green, and blue color values for a single index in a Surface palette. The index should be a value from 0 to 255.
New in pygame 1.9: Returning Color(with length 3) instance instead of a tuple.
Set the full palette for an 8-bit Surface. This will replace the colors in the existing palette. A partial palette can be passed and only the first colors in the original palette will be changed.
This function has no effect on a Surface with more than 8-bits per pixel.
Set the palette value for a single entry in a Surface palette. The index should be a value from 0 to 255.
This function has no effect on a Surface with more than 8-bits per pixel.
Convert an RGBA color into the mapped integer value for this Surface. The returned integer will contain no more bits than the bit depth of the Surface. Mapped color values are not often used inside pygame, but can be passed to most functions that require a Surface and a color.
See the Surface object documentation for more information about colors and pixel formats.
Convert an mapped integer color into the RGB color components for this Surface. Mapped color values are not often used inside pygame, but can be passed to most functions that require a Surface and a color.
See the Surface object documentation for more information about colors and pixel formats.
Each Surface has an active clipping area. This is a rectangle that represents the only pixels on the Surface that can be modified. If None is passed for the rectangle the full Surface will be available for changes.
The clipping area is always restricted to the area of the Surface itself. If the clip rectangle is too large it will be shrunk to fit inside the Surface.
Return a rectangle of the current clipping area. The Surface will always return a valid rectangle that will never be outside the bounds of the image. If the Surface has had None set for the clipping area, the Surface will return a rectangle with the full area of the Surface.
Returns a new Surface that shares its pixels with its new parent. The new Surface is considered a child of the original. Modifications to either Surface pixels will effect each other. Surface information like clipping area and color keys are unique to each Surface.
The new Surface will inherit the palette, color key, and alpha settings from its parent.
It is possible to have any number of subsurfaces and subsubsurfaces on the parent. It is also possible to subsurface the display Surface if the display mode is not hardware accelerated.
See get_offset() and get_parent() to learn more about the state of a subsurface.
A subsurface will have the same class as the parent surface.
Returns the parent Surface of a subsurface. If this is not a subsurface then None will be returned.
Returns the parent Surface of a subsurface. If this is not a subsurface then this surface will be returned.
Get the offset position of a child subsurface inside of a parent. If the Surface is not a subsurface this will return (0, 0).
Get the offset position of a child subsurface inside of its top level parent Surface. If the Surface is not a subsurface this will return (0, 0).
Return the width and height of the Surface in pixels.
Return the width of the Surface in pixels.
Return the height of the Surface in pixels.
Returns a new rectangle covering the entire surface. This rectangle will always start at (0, 0) with a width and height the same size as the image.
You can pass keyword argument values to this function. These named values will be applied to the attributes of the Rect before it is returned. An example would be mysurf.get_rect(center=(100, 100)) to create a rectangle for the Surface centered at a given position.
Returns the number of bits used to represent each pixel. This value may not exactly fill the number of bytes used per pixel. For example a 15 bit Surface still requires a full 2 bytes.
Return the number of bytes used per pixel.
Returns a set of current Surface features. Each feature is a bit in the flags bitmask. Typical flags are HWSURFACE, RLEACCEL, SRCALPHA, and SRCCOLORKEY.
Here is a more complete list of flags. A full list can be found in SDL_video.h
Available for pygame.display.set_mode()
Used internally (read-only)
Return the number of bytes separating each row in the Surface. Surfaces in video memory are not always linearly packed. Subsurfaces will also have a larger pitch than their real width.
This value is not needed for normal pygame usage.
Returns the bitmasks used to isolate each color in a mapped integer.
This value is not needed for normal pygame usage.
This is not needed for normal pygame usage.
Note
In SDL2, the masks are read-only and accordingly this method will raise an AttributeError if called.
New in pygame 1.8.1.
Returns the pixel shifts need to convert between each color and a mapped integer.
This value is not needed for normal pygame usage.
This is not needed for normal pygame usage.
Note
In SDL2, the shifts are read-only and accordingly this method will raise an AttributeError if called.
New in pygame 1.8.1.
Return the least significant number of bits stripped from each color in a mapped integer.
This value is not needed for normal pygame usage.
Returns the smallest rectangular region that contains all the pixels in the surface that have an alpha value greater than or equal to the minimum alpha value.
This function will temporarily lock and unlock the Surface as needed.
New in pygame 1.8.
Return an object which exports a surface's internal pixel buffer as a C level array struct, Python level array interface or a C level buffer interface. The pixel buffer is writeable. The new buffer protocol is supported for Python 2.6 and up in CPython. The old buffer protocol is also supported for Python 2.x. The old buffer data is in one segment for kind '0', multi-segment for other buffer view kinds.
The kind argument is the length 1 string '0', '1', '2', '3', 'r', 'g', 'b', or 'a'. The letters are case insensitive; 'A' will work as well. The argument can be either a Unicode or byte (char) string. The default is '2'.
'0' returns a contiguous unstructured bytes view. No surface shape information is given. A ValueError is raised if the surface's pixels are discontinuous.
'1' returns a (surface-width * surface-height) array of continuous pixels. A ValueError is raised if the surface pixels are discontinuous.
'2' returns a (surface-width, surface-height) array of raw pixels. The pixels are surface-bytesize-d unsigned integers. The pixel format is surface specific. The 3 byte unsigned integers of 24 bit surfaces are unlikely accepted by anything other than other pygame functions.
'3' returns a (surface-width, surface-height, 3) array of RGB color components. Each of the red, green, and blue components are unsigned bytes. Only 24-bit and 32-bit surfaces are supported. The color components must be in either RGB or BGR order within the pixel.
'r' for red, 'g' for green, 'b' for blue, and 'a' for alpha return a (surface-width, surface-height) view of a single color component within a surface: a color plane. Color components are unsigned bytes. Both 24-bit and 32-bit surfaces support 'r', 'g', and 'b'. Only 32-bit surfaces with SRCALPHA support 'a'.
The surface is locked only when an exposed interface is accessed. For new buffer interface accesses, the surface is unlocked once the last buffer view is released. For array interface and old buffer interface accesses, the surface remains locked until the BufferProxy object is released.
New in pygame 1.9.2.
Return a buffer object for the pixels of the Surface. The buffer can be used for direct pixel access and manipulation. Surface pixel data is represented as an unstructured block of memory, with a start address and length in bytes. The data need not be contiguous. Any gaps are included in the length, but otherwise ignored.
This method implicitly locks the Surface. The lock will be released when the returned pygame.BufferProxy object is garbage collected.
New in pygame 1.8.
The starting address of the surface's raw pixel bytes.
New in pygame 1.9.2.


The starting address of the surface's raw pixel bytes.
New in pygame 1.9.2.


Draws a source Surface onto this Surface. The draw can be positioned with the dest argument. The dest argument can either be a pair of coordinates representing the position of the upper left corner of the blit or a Rect, where the upper left corner of the rectangle will be used as the position for the blit. The size of the destination rectangle does not effect the blit.
An optional area rectangle can be passed as well. This represents a smaller portion of the source Surface to draw.
New in pygame 1.8: Optional special_flags: BLEND_ADD, BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX.
New in pygame 1.8.1: Optional special_flags: BLEND_RGBA_ADD, BLEND_RGBA_SUB, BLEND_RGBA_MULT, BLEND_RGBA_MIN, BLEND_RGBA_MAX BLEND_RGB_ADD, BLEND_RGB_SUB, BLEND_RGB_MULT, BLEND_RGB_MIN, BLEND_RGB_MAX.
New in pygame 1.9.2: Optional special_flags: BLEND_PREMULTIPLIED
New in pygame 2.0.0: Optional special_flags: BLEND_ALPHA_SDL2 - Uses the SDL2 blitter for alpha blending, this gives different results than the default blitter, which is modelled after SDL1, due to different approximations used for the alpha blending formula. The SDL2 blitter also supports RLE on alpha blended surfaces which the pygame one does not.
The return rectangle is the area of the affected pixels, excluding any pixels outside the destination Surface, or outside the clipping area.
Pixel alphas will be ignored when blitting to an 8 bit Surface.
For a surface with colorkey or blanket alpha, a blit to self may give slightly different colors than a non self-blit.


Draws many surfaces onto this Surface. It takes a sequence as input, with each of the elements corresponding to the ones of blit(). It needs at minimum a sequence of (source, dest).
a list of rects of the areas changed if doreturn is True, otherwise None
list or None
New in pygame 1.9.4.


Creates a new copy of the Surface with the pixel format changed. The new pixel format can be determined from another existing Surface. Otherwise depth, flags, and masks arguments can be used, similar to the pygame.Surface() call.
If no arguments are passed the new Surface will have the same pixel format as the display Surface. This is always the fastest format for blitting. It is a good idea to convert all Surfaces before they are blitted many times.
The converted Surface will have no pixel alphas. They will be stripped if the original had them. See convert_alpha() for preserving or creating per-pixel alphas.
The new copy will have the same class as the copied surface. This lets as Surface subclass inherit this method without the need to override, unless subclass specific instance attributes also need copying.


Creates a new copy of the surface with the desired pixel format. The new surface will be in a format suited for quick blitting to the given format with per pixel alpha. If no surface is given, the new surface will be optimized for blitting to the current display.
Unlike the convert() method, the pixel format for the new image will not be exactly the same as the requested source, but it will be optimized for fast alpha blitting to the destination.
As with convert() the returned surface has the same class as the converted surface.


Makes a duplicate copy of a Surface. The new surface will have the same pixel formats, color palettes, transparency settings, and class as the original. If a Surface subclass also needs to copy any instance specific attributes then it should override copy().


Fill the Surface with a solid color. If no rect argument is given the entire Surface will be filled. The rect argument will limit the fill to a specific area. The fill will also be contained by the Surface clip area.
The color argument can be either a RGB sequence, a RGBA sequence or a mapped color index. If using RGBA, the Alpha (A part of RGBA) is ignored unless the surface uses per pixel alpha (Surface has the SRCALPHA flag).
New in pygame 1.8: Optional special_flags: BLEND_ADD, BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX.
New in pygame 1.8.1: Optional special_flags: BLEND_RGBA_ADD, BLEND_RGBA_SUB, BLEND_RGBA_MULT, BLEND_RGBA_MIN, BLEND_RGBA_MAX BLEND_RGB_ADD, BLEND_RGB_SUB, BLEND_RGB_MULT, BLEND_RGB_MIN, BLEND_RGB_MAX.
This will return the affected Surface area.


Get the offset position of a child subsurface inside of its top level parent Surface. If the Surface is not a subsurface this will return (0, 0).


Returns the parent Surface of a subsurface. If this is not a subsurface then this surface will be returned.


Return the current alpha value for the Surface.


Return a copy of the RGBA Color value at the given pixel. If the Surface has no per pixel alpha, then the alpha value will always be 255 (opaque). If the pixel position is outside the area of the Surface an IndexError exception will be raised.
Getting and setting pixels one at a time is generally too slow to be used in a game or realtime situation. It is better to use methods which operate on many pixels at a time like with the blit, fill and draw methods - or by using pygame.surfarray/pygame.PixelArray.
This function will temporarily lock and unlock the Surface as needed.
New in pygame 1.9: Returning a Color instead of tuple. Use tuple(surf.get_at((x,y))) if you want a tuple, and not a Color. This should only matter if you want to use the color as a key in a dict.


Return the integer value of the given pixel. If the pixel position is outside the area of the Surface an IndexError exception will be raised.
This method is intended for pygame unit testing. It unlikely has any use in an application.
This function will temporarily lock and unlock the Surface as needed.
New in pygame 1.9.2.


Returns the number of bits used to represent each pixel. This value may not exactly fill the number of bytes used per pixel. For example a 15 bit Surface still requires a full 2 bytes.


Returns the smallest rectangular region that contains all the pixels in the surface that have an alpha value greater than or equal to the minimum alpha value.
This function will temporarily lock and unlock the Surface as needed.
New in pygame 1.8.


Return a buffer object for the pixels of the Surface. The buffer can be used for direct pixel access and manipulation. Surface pixel data is represented as an unstructured block of memory, with a start address and length in bytes. The data need not be contiguous. Any gaps are included in the length, but otherwise ignored.
This method implicitly locks the Surface. The lock will be released when the returned pygame.BufferProxy object is garbage collected.
New in pygame 1.8.


Return the number of bytes used per pixel.


Return a rectangle of the current clipping area. The Surface will always return a valid rectangle that will never be outside the bounds of the image. If the Surface has had None set for the clipping area, the Surface will return a rectangle with the full area of the Surface.


Return the current colorkey value for the Surface. If the colorkey is not set then None is returned.


Returns a set of current Surface features. Each feature is a bit in the flags bitmask. Typical flags are HWSURFACE, RLEACCEL, SRCALPHA, and SRCCOLORKEY.
Here is a more complete list of flags. A full list can be found in SDL_video.h
Available for pygame.display.set_mode()
Used internally (read-only)


Return the height of the Surface in pixels.


Returns True when the Surface is locked. It doesn't matter how many times the Surface is locked.


Returns the currently existing locks for the Surface.


Return the least significant number of bits stripped from each color in a mapped integer.
This value is not needed for normal pygame usage.


Returns the bitmasks used to isolate each color in a mapped integer.
This value is not needed for normal pygame usage.


Get the offset position of a child subsurface inside of a parent. If the Surface is not a subsurface this will return (0, 0).


Return a list of up to 256 color elements that represent the indexed colors used in an 8-bit Surface. The returned list is a copy of the palette, and changes will have no effect on the Surface.
Returning a list of Color(with length 3) instances instead of tuples.
New in pygame 1.9.


Returns the red, green, and blue color values for a single index in a Surface palette. The index should be a value from 0 to 255.
New in pygame 1.9: Returning Color(with length 3) instance instead of a tuple.


Returns the parent Surface of a subsurface. If this is not a subsurface then None will be returned.


Return the number of bytes separating each row in the Surface. Surfaces in video memory are not always linearly packed. Subsurfaces will also have a larger pitch than their real width.
This value is not needed for normal pygame usage.


Returns a new rectangle covering the entire surface. This rectangle will always start at (0, 0) with a width and height the same size as the image.
You can pass keyword argument values to this function. These named values will be applied to the attributes of the Rect before it is returned. An example would be mysurf.get_rect(center=(100, 100)) to create a rectangle for the Surface centered at a given position.


Returns the pixel shifts need to convert between each color and a mapped integer.
This value is not needed for normal pygame usage.


Return the width and height of the Surface in pixels.


Return an object which exports a surface's internal pixel buffer as a C level array struct, Python level array interface or a C level buffer interface. The pixel buffer is writeable. The new buffer protocol is supported for Python 2.6 and up in CPython. The old buffer protocol is also supported for Python 2.x. The old buffer data is in one segment for kind '0', multi-segment for other buffer view kinds.
The kind argument is the length 1 string '0', '1', '2', '3', 'r', 'g', 'b', or 'a'. The letters are case insensitive; 'A' will work as well. The argument can be either a Unicode or byte (char) string. The default is '2'.
'0' returns a contiguous unstructured bytes view. No surface shape information is given. A ValueError is raised if the surface's pixels are discontinuous.
'1' returns a (surface-width * surface-height) array of continuous pixels. A ValueError is raised if the surface pixels are discontinuous.
'2' returns a (surface-width, surface-height) array of raw pixels. The pixels are surface-bytesize-d unsigned integers. The pixel format is surface specific. The 3 byte unsigned integers of 24 bit surfaces are unlikely accepted by anything other than other pygame functions.
'3' returns a (surface-width, surface-height, 3) array of RGB color components. Each of the red, green, and blue components are unsigned bytes. Only 24-bit and 32-bit surfaces are supported. The color components must be in either RGB or BGR order within the pixel.
'r' for red, 'g' for green, 'b' for blue, and 'a' for alpha return a (surface-width, surface-height) view of a single color component within a surface: a color plane. Color components are unsigned bytes. Both 24-bit and 32-bit surfaces support 'r', 'g', and 'b'. Only 32-bit surfaces with SRCALPHA support 'a'.
The surface is locked only when an exposed interface is accessed. For new buffer interface accesses, the surface is unlocked once the last buffer view is released. For array interface and old buffer interface accesses, the surface remains locked until the BufferProxy object is released.
New in pygame 1.9.2.


Return the width of the Surface in pixels.


Lock the pixel data of a Surface for access. On accelerated Surfaces, the pixel data may be stored in volatile video memory or nonlinear compressed forms. When a Surface is locked the pixel memory becomes available to access by regular software. Code that reads or writes pixel values will need the Surface to be locked.
Surfaces should not remain locked for more than necessary. A locked Surface can often not be displayed or managed by pygame.
Not all Surfaces require locking. The mustlock() method can determine if it is actually required. There is no performance penalty for locking and unlocking a Surface that does not need it.
All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.
It is safe to nest locking and unlocking calls. The surface will only be unlocked after the final lock is released.


Convert an RGBA color into the mapped integer value for this Surface. The returned integer will contain no more bits than the bit depth of the Surface. Mapped color values are not often used inside pygame, but can be passed to most functions that require a Surface and a color.
See the Surface object documentation for more information about colors and pixel formats.


Returns True if the Surface is required to be locked to access pixel data. Usually pure software Surfaces do not require locking. This method is rarely needed, since it is safe and quickest to just lock all Surfaces as needed.
All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.


Move the image by dx pixels right and dy pixels down. dx and dy may be negative for left and up scrolls respectively. Areas of the surface that are not overwritten retain their original pixel values. Scrolling is contained by the Surface clip area. It is safe to have dx and dy values that exceed the surface size.
New in pygame 1.9.


Set the current alpha value for the Surface. When blitting this Surface onto a destination, the pixels will be drawn slightly transparent. The alpha value is an integer from 0 to 255, 0 is fully transparent and 255 is fully opaque. If None is passed for the alpha value, then alpha blending will be disabled, including per-pixel alpha.
This value is different than the per pixel Surface alpha. For a surface with per pixel alpha, blanket alpha is ignored and None is returned.
Changed in pygame 2.0: per-surface alpha can be combined with per-pixel alpha.
The optional flags argument can be set to pygame.RLEACCEL to provide better performance on non accelerated displays. An RLEACCEL Surface will be slower to modify, but quicker to blit as a source.


Set the RGBA or mapped integer color value for a single pixel. If the Surface does not have per pixel alphas, the alpha value is ignored. Setting pixels outside the Surface area or outside the Surface clipping will have no effect.
Getting and setting pixels one at a time is generally too slow to be used in a game or realtime situation.
This function will temporarily lock and unlock the Surface as needed.


Each Surface has an active clipping area. This is a rectangle that represents the only pixels on the Surface that can be modified. If None is passed for the rectangle the full Surface will be available for changes.
The clipping area is always restricted to the area of the Surface itself. If the clip rectangle is too large it will be shrunk to fit inside the Surface.


Set the current color key for the Surface. When blitting this Surface onto a destination, any pixels that have the same color as the colorkey will be transparent. The color can be an RGB color or a mapped color integer. If None is passed, the colorkey will be unset.
The colorkey will be ignored if the Surface is formatted to use per pixel alpha values. The colorkey can be mixed with the full Surface alpha value.
The optional flags argument can be set to pygame.RLEACCEL to provide better performance on non accelerated displays. An RLEACCEL Surface will be slower to modify, but quicker to blit as a source.


This is not needed for normal pygame usage.
Note
In SDL2, the masks are read-only and accordingly this method will raise an AttributeError if called.
New in pygame 1.8.1.


Set the full palette for an 8-bit Surface. This will replace the colors in the existing palette. A partial palette can be passed and only the first colors in the original palette will be changed.
This function has no effect on a Surface with more than 8-bits per pixel.


Set the palette value for a single entry in a Surface palette. The index should be a value from 0 to 255.
This function has no effect on a Surface with more than 8-bits per pixel.


This is not needed for normal pygame usage.
Note
In SDL2, the shifts are read-only and accordingly this method will raise an AttributeError if called.
New in pygame 1.8.1.


Returns a new Surface that shares its pixels with its new parent. The new Surface is considered a child of the original. Modifications to either Surface pixels will effect each other. Surface information like clipping area and color keys are unique to each Surface.
The new Surface will inherit the palette, color key, and alpha settings from its parent.
It is possible to have any number of subsurfaces and subsubsurfaces on the parent. It is also possible to subsurface the display Surface if the display mode is not hardware accelerated.
See get_offset() and get_parent() to learn more about the state of a subsurface.
A subsurface will have the same class as the parent surface.


Unlock the Surface pixel data after it has been locked. The unlocked Surface can once again be drawn and managed by pygame. See the lock() documentation for more details.
All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.
It is safe to nest locking and unlocking calls. The surface will only be unlocked after the final lock is released.


Convert an mapped integer color into the RGB color components for this Surface. Mapped color values are not often used inside pygame, but can be passed to most functions that require a Surface and a color.
See the Surface object documentation for more information about colors and pixel formats.


Copy the mapped (raw) pixels from a Surface into a 2D array. The bit depth of the surface will control the size of the integer values, and will work for any type of pixel format.
This function will temporarily lock the Surface as pixels are copied (see the pygame.Surface.lock() - lock the Surface memory for pixel access method).


Copy the pixels from a Surface into a 3D array. The bit depth of the surface will control the size of the integer values, and will work for any type of pixel format.
This function will temporarily lock the Surface as pixels are copied (see the pygame.Surface.lock() - lock the Surface memory for pixel access method).


Copy the pixel alpha values (degree of transparency) from a Surface into a 2D array. This will work for any type of Surface format. Surfaces without a pixel alpha will return an array with all opaque values.
This function will temporarily lock the Surface as pixels are copied (see the pygame.Surface.lock() - lock the Surface memory for pixel access method).


Create a new array with the colorkey transparency value from each pixel. If the pixel matches the colorkey it will be fully transparent; otherwise it will be fully opaque.
This will work on any type of Surface format. If the image has no colorkey a solid opaque array will be returned.
This function will temporarily lock the Surface as pixels are copied.


Directly copy values from an array into a Surface. This is faster than converting the array into a Surface and blitting. The array must be the same dimensions as the Surface and will completely replace all pixel values. Only integer, ASCII character and record arrays are accepted.
This function will temporarily lock the Surface as the new values are copied.


DEPRECATED: Returns the currently active array type. This will be a value of the get_arraytypes() tuple and indicates which type of array module is used for the array creation.
New in pygame 1.8.


DEPRECATED: Checks, which array systems are available and returns them as a tuple of strings. The values of the tuple can be used directly in the pygame.surfarray.use_arraytype() () method. If no supported array system could be found, None will be returned.
New in pygame 1.8.


Create a new Surface that best resembles the data and format on the array. The array can be 2D or 3D with any sized integer values. Function make_surface uses the array struct interface to acquire array properties, so is not limited to just NumPy arrays. See pygame.pixelcopy.
New in pygame 1.9.2: array struct interface support.


Convert a 3D array into a 2D array. This will use the given Surface format to control the conversion. Palette surface formats are supported for NumPy arrays.


Create a new 2D array that directly references the pixel values in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
Pixels from a 24-bit Surface cannot be referenced, but all other Surface bit depths can.
The Surface this references will remain locked for the lifetime of the array (see the pygame.Surface.lock() - lock the Surface memory for pixel access method).


Create a new 3D array that directly references the pixel values in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
This will only work on Surfaces that have 24-bit or 32-bit formats. Lower pixel formats cannot be referenced.
The Surface this references will remain locked for the lifetime of the array (see the pygame.Surface.lock() - lock the Surface memory for pixel access method).


Create a new 2D array that directly references the alpha values (degree of transparency) in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
This can only work on 32-bit Surfaces with a per-pixel alpha value.
The Surface this array references will remain locked for the lifetime of the array.


Create a new 2D array that directly references the blue values in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
This can only work on 24-bit or 32-bit Surfaces.
The Surface this array references will remain locked for the lifetime of the array.


Create a new 2D array that directly references the green values in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
This can only work on 24-bit or 32-bit Surfaces.
The Surface this array references will remain locked for the lifetime of the array.


Create a new 2D array that directly references the red values in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
This can only work on 24-bit or 32-bit Surfaces.
The Surface this array references will remain locked for the lifetime of the array.


DEPRECATED: Uses the requested array type for the module functions. The only supported arraytype is 'numpy'. Other values will raise ValueError.


Positional arguments (optional):
Keyword arguments:
Return value:
By default individual test modules are run in separate subprocesses. This recreates normal pygame usage where pygame.init() and pygame.quit() are called only once per program execution, and avoids unfortunate interactions between test modules. Also, a time limit is placed on test execution, so frozen tests are killed when there time allotment expired. Use the single process option if threading is not working properly or if tests are taking too long. It is not guaranteed that all tests will pass in single process mode.
Tests are run in a randomized order if the randomize argument is True or a seed argument is provided. If no seed integer is provided then the system time is used.
Individual test modules may have a __tags__ attribute, a list of tag strings used to selectively omit modules from a run. By default only 'interactive' modules such as cdrom_test are ignored. An interactive module must be run from the console as a Python program.
This function can only be called once per Python session. It is not reentrant.


Creates a new Clock object that can be used to track an amount of time. The clock also provides several functions to help control a game's framerate.
This method should be called once per frame. It will compute how many milliseconds have passed since the previous call.
If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. This can be used to help limit the runtime speed of a game. By calling Clock.tick(40) once per frame, the program will never run at more than 40 frames per second.
Note that this function uses SDL_Delay function which is not accurate on every platform, but does not use much CPU. Use tick_busy_loop if you want an accurate timer, and don't mind chewing CPU.
This method should be called once per frame. It will compute how many milliseconds have passed since the previous call.
If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. This can be used to help limit the runtime speed of a game. By calling Clock.tick_busy_loop(40) once per frame, the program will never run at more than 40 frames per second.
Note that this function uses pygame.time.delay(), which uses lots of CPU in a busy loop to make sure that timing is more accurate.
New in pygame 1.8.
The number of milliseconds that passed between the previous two calls to Clock.tick().
Similar to Clock.get_time(), but does not include any time used while Clock.tick() was delaying to limit the framerate.
Compute your game's framerate (in frames per second). It is computed by averaging the last ten calls to Clock.tick().


Compute your game's framerate (in frames per second). It is computed by averaging the last ten calls to Clock.tick().


Similar to Clock.get_time(), but does not include any time used while Clock.tick() was delaying to limit the framerate.


The number of milliseconds that passed between the previous two calls to Clock.tick().


This method should be called once per frame. It will compute how many milliseconds have passed since the previous call.
If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. This can be used to help limit the runtime speed of a game. By calling Clock.tick(40) once per frame, the program will never run at more than 40 frames per second.
Note that this function uses SDL_Delay function which is not accurate on every platform, but does not use much CPU. Use tick_busy_loop if you want an accurate timer, and don't mind chewing CPU.


This method should be called once per frame. It will compute how many milliseconds have passed since the previous call.
If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. This can be used to help limit the runtime speed of a game. By calling Clock.tick_busy_loop(40) once per frame, the program will never run at more than 40 frames per second.
Note that this function uses pygame.time.delay(), which uses lots of CPU in a busy loop to make sure that timing is more accurate.
New in pygame 1.8.


Will pause for a given number of milliseconds. This function will use the processor (rather than sleeping) in order to make the delay more accurate than pygame.time.wait().
This returns the actual number of milliseconds used.


Return the number of milliseconds since pygame.init() was called. Before pygame is initialized this will always be 0.


Set an event type to appear on the event queue every given number of milliseconds. The first event will not appear until the amount of time has passed.
Every event type can have a separate timer attached to it. It is best to use the value between pygame.USEREVENT and pygame.NUMEVENTS.
To disable the timer for an event, set the milliseconds argument to 0.
If the once argument is True, then only send the timer once.
New in pygame 2.0.0.dev3: once argument added.


Will pause for a given number of milliseconds. This function sleeps the process to share the processor with other programs. A program that waits for even a few milliseconds will consume very little processor time. It is slightly less accurate than the pygame.time.delay() function.
This returns the actual number of milliseconds used.


Finds the average color of a Surface or a region of a surface specified by a Rect, and returns it as a Color.


Takes a sequence of surfaces and returns a surface with average colors from each of the surfaces.
palette_colors - if true we average the colors in palette, otherwise we average the pixel values. This is useful if the surface is actually greyscale colors, and not palette colors.
Note, this function currently does not handle palette using surfaces correctly.
New in pygame 1.8.
New in pygame 1.9: palette_colors argument


Extracts a portion of an image. All vertical and horizontal pixels surrounding the given rectangle area are removed. The corner areas (diagonal to the rect) are then brought together. (The original image is not altered by this operation.)
NOTE: If you want a "crop" that returns the part of an image within a rect, you can blit with a rect to a new surface or copy a subsurface.


This can flip a Surface either vertically, horizontally, or both. Flipping a Surface is non-destructive and returns a new Surface with the same dimensions.


Shows whether or not smoothscale is using MMX or SSE acceleration. If no acceleration is available then "GENERIC" is returned. For a x86 processor the level of acceleration to use is determined at runtime.
This function is provided for pygame testing and debugging.


Finds the edges in a surface using the laplacian algorithm.
New in pygame 1.8.


Unfiltered counterclockwise rotation. The angle argument represents degrees and can be any floating point value. Negative angle amounts will rotate clockwise.
Unless rotating by 90 degree increments, the image will be padded larger to hold the new size. If the image has pixel alphas, the padded area will be transparent. Otherwise pygame will pick a color that matches the Surface colorkey or the topleft pixel value.


This is a combined scale and rotation transform. The resulting Surface will be a filtered 32-bit Surface. The scale argument is a floating point value that will be multiplied by the current resolution. The angle argument is a floating point value that represents the counterclockwise degrees to rotate. A negative rotation angle will rotate clockwise.


Resizes the Surface to a new resolution. This is a fast scale operation that does not sample the results.
An optional destination surface can be used, rather than have it create a new one. This is quicker if you want to repeatedly scale something. However the destination must be the same size as the (width, height) passed in. Also the destination surface must be the same format.


This will return a new image that is double the size of the original. It uses the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap graphics.
This really only has an effect on simple images with solid colors. On photographic and antialiased images it will look like a regular unfiltered scale.
An optional destination surface can be used, rather than have it create a new one. This is quicker if you want to repeatedly scale something. However the destination must be twice the size of the source surface passed in. Also the destination surface must be the same format.


Sets smoothscale acceleration. Takes a string argument. A value of 'GENERIC' turns off acceleration. 'MMX' uses MMX instructions only. 'SSE' allows SSE extensions as well. A value error is raised if type is not recognized or not supported by the current processor.
This function is provided for pygame testing and debugging. If smoothscale causes an invalid instruction error then it is a pygame/SDL bug that should be reported. Use this function as a temporary fix only.


Uses one of two different algorithms for scaling each dimension of the input surface as required. For shrinkage, the output pixels are area averages of the colors they cover. For expansion, a bilinear filter is used. For the x86-64 and i686 architectures, optimized MMX routines are included and will run much faster than other machine types. The size is a 2 number sequence for (width, height). This function only works for 24-bit or 32-bit surfaces. An exception will be thrown if the input surface bit depth is less than 24.
New in pygame 1.8.


This versatile function can be used for find colors in a 'surf' close to a 'search_color' or close to colors in a separate 'search_surf'.
It can also be used to transfer pixels into a 'dest_surf' that match or don't match.
By default it sets pixels in the 'dest_surf' where all of the pixels NOT within the threshold are changed to set_color. If inverse_set is optionally set to True, the pixels that ARE within the threshold are changed to set_color.
If the optional 'search_surf' surface is given, it is used to threshold against rather than the specified 'set_color'. That is, it will find each pixel in the 'surf' that is within the 'threshold' of the pixel at the same coordinates of the 'search_surf'.
int
The number of pixels that are within the 'threshold' in 'surf' compared to either 'search_color' or search_surf.
See the threshold tests for a full of examples: https://github.com/pygame/pygame/blob/master/test/transform_test.py
New in pygame 1.8.
Changed in pygame 1.9.4: Fixed a lot of bugs and added keyword arguments. Test your code.


The Mercurial node identifier of the repository checkout from which this package was built. If the identifier ends with a plus sign '+' then the package contains uncommitted changes. Please include this revision number in bug reports, especially for non-release pygame builds.
Important note: pygame development has moved to github, this variable is obsolete now. As soon as development shifted to github, this variable started returning an empty string "". It has always been returning an empty string since v1.9.5.
Changed in pygame 1.9.5: Always returns an empty string "".


This is the SDL library version represented as an extended tuple. It also has attributes 'major', 'minor' & 'patch' that can be accessed like this:
printing the whole thing returns a string like this:
New in pygame 2.0.0.


This is the version represented as a string. It can contain a micro release number as well, e.g. '1.5.2'


This version information can easily be compared with other version numbers of the same format. An example of checking pygame version numbers would look like this:
New in pygame 1.9.6: Attributes major, minor, and patch.
Changed in pygame 1.9.6: str(pygame.version.vernum) returns a string like "2.0.0" instead of "(2, 0, 0)".
Changed in pygame 1.9.6: repr(pygame.version.vernum) returns a string like "PygameVersion(major=2, minor=0, patch=0)" instead of "(2, 0, 0)".


This is a repository for short and sweet examples and links for useful pandas recipes. We encourage users to add to this documentation.
Adding interesting links and/or inline examples to this section is a great First Pull Request.
Simplified, condensed, new-user friendly, in-line examples have been inserted where possible to augment the Stack-Overflow and GitHub links. Many of the links contain expanded information, above what the in-line examples offer.
pandas (pd) and NumPy (np) are the only two abbreviated imported modules. The rest are kept explicitly imported for newer users.
These are some neat pandas idioms
if-then/if-then-else on one column, and assignment to another one or more columns:
An if-then on one column
An if-then with assignment to 2 columns:
Add another line with different logic, to do the -else
Or use pandas where after you’ve set up a mask
if-then-else using NumPy’s where()
Split a frame with a boolean criterion
Select with multi-column criteria
…and (without assignment returns a Series)
…or (without assignment returns a Series)
…or (with assignment modifies the DataFrame.)
Select rows with data closest to certain value using argsort
Dynamically reduce a list of criteria using a binary operators
One could hard code:
…Or it can be done with a list of dynamically built criteria
The indexing docs.
Using both row labels and value conditionals
Use loc for label-oriented slicing and iloc positional slicing GH2904
There are 2 explicit slicing methods, with a third general case
Positional-oriented (Python slicing style : exclusive of end)
Label-oriented (Non-Python slicing style : inclusive of end)
General (Either slicing style : depends on if the slice contains labels or positions)
Ambiguity arises when an index consists of integers with a non-zero start or non-unit increment.
Using inverse operator (~) to take the complement of a mask
Efficiently and dynamically creating new columns using applymap
Keep other columns when using min() with groupby
Method 1 : idxmin() to get the index of the minimums
Method 2 : sort then take first of each
Notice the same results, with the exception of the index.
The multindexing docs.
Creating a MultiIndex from a labeled frame
Performing arithmetic with a MultiIndex that needs broadcasting
Slicing a MultiIndex with xs
To take the cross section of the 1st level and 1st axis the index:
…and now the 2nd level of the 1st axis.
Slicing a MultiIndex with xs, method #2
Setting portions of a MultiIndex with xs
Sort by specific column or an ordered list of columns, with a MultiIndex
Partial selection, the need for sortedness GH2995
Prepending a level to a multiindex
Flatten Hierarchical columns
The missing data docs.
Fill forward a reversed timeseries
cumsum reset at NaN values
Using replace with backrefs
The grouping docs.
Basic grouping with apply
Unlike agg, apply’s callable is passed a sub-DataFrame which gives you access to all the columns
Using get_group
Apply to different items in a group
Expanding apply
Replacing some values with mean of the rest of a group
Sort groups by aggregated data
Create multiple aggregated columns
Create a value counts column and reassign back to the DataFrame
Shift groups of the values in a column based on the index
Select row with maximum value from each group
Grouping like Python’s itertools.groupby
Alignment and to-date
Rolling Computation window based on values instead of counts
Rolling Mean by Time Interval
Splitting a frame
Create a list of dataframes, split using a delineation based on logic included in rows.
The Pivot docs.
Partial sums and subtotals
Frequency table like plyr in R
Plot pandas DataFrame with year over year data
To create year and month cross tabulation:
Rolling apply to organize - Turning embedded lists into a MultiIndex frame
Rolling apply with a DataFrame returning a Series
Rolling Apply to multiple columns where function calculates a Series before a Scalar from the Series is returned
Rolling apply with a DataFrame returning a Scalar
Rolling Apply to multiple columns where function returns a Scalar (Volume Weighted Average Price)
Between times
Using indexer between time
Constructing a datetime range that excludes weekends and includes only certain times
Vectorized Lookup
Aggregation and plotting time series
Turn a matrix with hours in columns and days in rows into a continuous row sequence in the form of a time series. How to rearrange a Python pandas DataFrame?
Dealing with duplicates when reindexing a timeseries to a specified frequency
Calculate the first day of the month for each entry in a DatetimeIndex
The Resample docs.
Using Grouper instead of TimeGrouper for time grouping of values
Time grouping with some missing values
Valid frequency arguments to Grouper Timeseries
Grouping using a MultiIndex
Using TimeGrouper and another grouping to create subgroups, then apply a custom function GH3791
Resampling with custom periods
Resample intraday frame without adding new days
Resample minute data
Resample with groupby
The Join docs.
Concatenate two dataframes with overlapping index (emulate R rbind)
Depending on df construction, ignore_index may be needed
Self Join of a DataFrame GH2996
How to set the index and join
KDB like asof join
Join with a criteria based on the values
Using searchsorted to merge based on values inside a range
The Plotting docs.
Make Matplotlib look like R
Setting x-axis major and minor labels
Plotting multiple charts in an IPython Jupyter notebook
Creating a multi-line plot
Plotting a heatmap
Annotate a time-series plot
Annotate a time-series plot #2
Generate Embedded plots in excel files using Pandas, Vincent and xlsxwriter
Boxplot for each quartile of a stratifying variable
Performance comparison of SQL vs HDF5
The CSV docs
read_csv in action
appending to a csv
Reading a csv chunk-by-chunk
Reading only certain rows of a csv chunk-by-chunk
Reading the first few lines of a frame
Reading a file that is compressed but not by gzip/bz2 (the native compressed formats which read_csv understands). This example shows a WinZipped file, but is a general application of opening the file within a context manager and using that handle to read. See here
Inferring dtypes from a file
Dealing with bad lines GH2886
Write a multi-row index CSV without writing duplicates
The best way to combine multiple files into a single DataFrame is to read the individual frames one by one, put all of the individual frames into a list, and then combine the frames in the list using pd.concat():
You can use the same approach to read all files matching a pattern. Here is an example using glob:
Finally, this strategy will work with the other pd.read_*(...) functions described in the io docs.
Parsing date components in multi-columns is faster with a format
The SQL docs
Reading from databases with SQL
The Excel docs
Reading from a filelike handle
Modifying formatting in XlsxWriter output
Loading only visible sheets GH19842#issuecomment-892150745
Reading HTML tables from a server that cannot handle the default request header
The HDFStores docs
Simple queries with a Timestamp Index
Managing heterogeneous data using a linked multiple table hierarchy GH3032
Merging on-disk tables with millions of rows
Avoiding inconsistencies when writing to a store from multiple processes/threads
De-duplicating a large store by chunks, essentially a recursive reduction operation. Shows a function for taking in data from csv file and creating a store by chunks, with date parsing as well. See here
Creating a store chunk-by-chunk from a csv file
Appending to a store, while creating a unique index
Large Data work flows
Reading in a sequence of files, then providing a global unique index to a store while appending
Groupby on a HDFStore with low group density
Groupby on a HDFStore with high group density
Hierarchical queries on a HDFStore
Counting with a HDFStore
Troubleshoot HDFStore exceptions
Setting min_itemsize with strings
Using ptrepack to create a completely-sorted-index on a store
Storing Attributes to a group node
You can create or load a HDFStore in-memory by passing the driver parameter to PyTables. Changes are only written to disk when the HDFStore is closed.
pandas readily accepts NumPy record arrays, if you need to read in a binary file consisting of an array of C structs. For example, given this C program in a file called main.c compiled with gcc main.c -std=gnu99 on a 64-bit machine,
the following Python code will read the binary file 'binary.dat' into a pandas DataFrame, where each element of the struct corresponds to a column in the frame:
Note
The offsets of the structure elements may be different depending on the architecture of the machine on which the file was created. Using a raw binary file format like this for general data storage is not recommended, as it is not cross platform. We recommended either HDF5 or parquet, both of which are supported by pandas’ IO facilities.
Numerical integration (sample-based) of a time series
Often it’s useful to obtain the lower (or upper) triangular form of a correlation matrix calculated from DataFrame.corr(). This can be achieved by passing a boolean mask to where as follows:
The method argument within DataFrame.corr can accept a callable in addition to the named correlation types. Here we compute the distance correlation matrix for a DataFrame object.
The Timedeltas docs.
Using timedeltas
Adding and subtracting deltas and dates
Another example
Values can be set to NaT using np.nan, similar to datetime
To create a dataframe from every combination of some given values, like R’s expand.grid() function, we can create a dict where the keys are column names and the values are lists of the data values:


DataFrame([data, index, columns, dtype, copy])
Two-dimensional, size-mutable, potentially heterogeneous tabular data.
Axes
DataFrame.index
The index (row labels) of the DataFrame.
DataFrame.columns
The column labels of the DataFrame.
DataFrame.dtypes
Return the dtypes in the DataFrame.
DataFrame.info([verbose, buf, max_cols, ...])
Print a concise summary of a DataFrame.
DataFrame.select_dtypes([include, exclude])
Return a subset of the DataFrame's columns based on the column dtypes.
DataFrame.values
Return a Numpy representation of the DataFrame.
DataFrame.axes
Return a list representing the axes of the DataFrame.
DataFrame.ndim
Return an int representing the number of axes / array dimensions.
DataFrame.size
Return an int representing the number of elements in this object.
DataFrame.shape
Return a tuple representing the dimensionality of the DataFrame.
DataFrame.memory_usage([index, deep])
Return the memory usage of each column in bytes.
DataFrame.empty
Indicator whether Series/DataFrame is empty.
DataFrame.set_flags(*[, copy, ...])
Return a new object with updated flags.
DataFrame.astype(dtype[, copy, errors])
Cast a pandas object to a specified dtype dtype.
DataFrame.convert_dtypes([infer_objects, ...])
Convert columns to best possible dtypes using dtypes supporting pd.NA.
DataFrame.infer_objects()
Attempt to infer better dtypes for object columns.
DataFrame.copy([deep])
Make a copy of this object's indices and data.
DataFrame.bool()
Return the bool of a single element Series or DataFrame.
DataFrame.head([n])
Return the first n rows.
DataFrame.at
Access a single value for a row/column label pair.
DataFrame.iat
Access a single value for a row/column pair by integer position.
DataFrame.loc
Access a group of rows and columns by label(s) or a boolean array.
DataFrame.iloc
Purely integer-location based indexing for selection by position.
DataFrame.insert(loc, column, value[, ...])
Insert column into DataFrame at specified location.
DataFrame.__iter__()
Iterate over info axis.
DataFrame.items()
Iterate over (column name, Series) pairs.
DataFrame.iteritems()
Iterate over (column name, Series) pairs.
DataFrame.keys()
Get the 'info axis' (see Indexing for more).
DataFrame.iterrows()
Iterate over DataFrame rows as (index, Series) pairs.
DataFrame.itertuples([index, name])
Iterate over DataFrame rows as namedtuples.
DataFrame.lookup(row_labels, col_labels)
(DEPRECATED) Label-based "fancy indexing" function for DataFrame.
DataFrame.pop(item)
Return item and drop from frame.
DataFrame.tail([n])
Return the last n rows.
DataFrame.xs(key[, axis, level, drop_level])
Return cross-section from the Series/DataFrame.
DataFrame.get(key[, default])
Get item from object for given key (ex: DataFrame column).
DataFrame.isin(values)
Whether each element in the DataFrame is contained in values.
DataFrame.where(cond[, other, inplace, ...])
Replace values where the condition is False.
DataFrame.mask(cond[, other, inplace, axis, ...])
Replace values where the condition is True.
DataFrame.query(expr[, inplace])
Query the columns of a DataFrame with a boolean expression.
For more information on .at, .iat, .loc, and .iloc, see the indexing documentation.
DataFrame.add(other[, axis, level, fill_value])
Get Addition of dataframe and other, element-wise (binary operator add).
DataFrame.sub(other[, axis, level, fill_value])
Get Subtraction of dataframe and other, element-wise (binary operator sub).
DataFrame.mul(other[, axis, level, fill_value])
Get Multiplication of dataframe and other, element-wise (binary operator mul).
DataFrame.div(other[, axis, level, fill_value])
Get Floating division of dataframe and other, element-wise (binary operator truediv).
DataFrame.truediv(other[, axis, level, ...])
Get Floating division of dataframe and other, element-wise (binary operator truediv).
DataFrame.floordiv(other[, axis, level, ...])
Get Integer division of dataframe and other, element-wise (binary operator floordiv).
DataFrame.mod(other[, axis, level, fill_value])
Get Modulo of dataframe and other, element-wise (binary operator mod).
DataFrame.pow(other[, axis, level, fill_value])
Get Exponential power of dataframe and other, element-wise (binary operator pow).
DataFrame.dot(other)
Compute the matrix multiplication between the DataFrame and other.
DataFrame.radd(other[, axis, level, fill_value])
Get Addition of dataframe and other, element-wise (binary operator radd).
DataFrame.rsub(other[, axis, level, fill_value])
Get Subtraction of dataframe and other, element-wise (binary operator rsub).
DataFrame.rmul(other[, axis, level, fill_value])
Get Multiplication of dataframe and other, element-wise (binary operator rmul).
DataFrame.rdiv(other[, axis, level, fill_value])
Get Floating division of dataframe and other, element-wise (binary operator rtruediv).
DataFrame.rtruediv(other[, axis, level, ...])
Get Floating division of dataframe and other, element-wise (binary operator rtruediv).
DataFrame.rfloordiv(other[, axis, level, ...])
Get Integer division of dataframe and other, element-wise (binary operator rfloordiv).
DataFrame.rmod(other[, axis, level, fill_value])
Get Modulo of dataframe and other, element-wise (binary operator rmod).
DataFrame.rpow(other[, axis, level, fill_value])
Get Exponential power of dataframe and other, element-wise (binary operator rpow).
DataFrame.lt(other[, axis, level])
Get Less than of dataframe and other, element-wise (binary operator lt).
DataFrame.gt(other[, axis, level])
Get Greater than of dataframe and other, element-wise (binary operator gt).
DataFrame.le(other[, axis, level])
Get Less than or equal to of dataframe and other, element-wise (binary operator le).
DataFrame.ge(other[, axis, level])
Get Greater than or equal to of dataframe and other, element-wise (binary operator ge).
DataFrame.ne(other[, axis, level])
Get Not equal to of dataframe and other, element-wise (binary operator ne).
DataFrame.eq(other[, axis, level])
Get Equal to of dataframe and other, element-wise (binary operator eq).
DataFrame.combine(other, func[, fill_value, ...])
Perform column-wise combine with another DataFrame.
DataFrame.combine_first(other)
Update null elements with value in the same location in other.
DataFrame.apply(func[, axis, raw, ...])
Apply a function along an axis of the DataFrame.
DataFrame.applymap(func[, na_action])
Apply a function to a Dataframe elementwise.
DataFrame.pipe(func, *args, **kwargs)
Apply chainable functions that expect Series or DataFrames.
DataFrame.agg([func, axis])
Aggregate using one or more operations over the specified axis.
DataFrame.aggregate([func, axis])
Aggregate using one or more operations over the specified axis.
DataFrame.transform(func[, axis])
Call func on self producing a DataFrame with the same axis shape as self.
DataFrame.groupby([by, axis, level, ...])
Group DataFrame using a mapper or by a Series of columns.
DataFrame.rolling(window[, min_periods, ...])
Provide rolling window calculations.
DataFrame.expanding([min_periods, center, ...])
Provide expanding window calculations.
DataFrame.ewm([com, span, halflife, alpha, ...])
Provide exponentially weighted (EW) calculations.
DataFrame.abs()
Return a Series/DataFrame with absolute numeric value of each element.
DataFrame.all([axis, bool_only, skipna, level])
Return whether all elements are True, potentially over an axis.
DataFrame.any([axis, bool_only, skipna, level])
Return whether any element is True, potentially over an axis.
DataFrame.clip([lower, upper, axis, inplace])
Trim values at input threshold(s).
DataFrame.corr([method, min_periods])
Compute pairwise correlation of columns, excluding NA/null values.
DataFrame.corrwith(other[, axis, drop, method])
Compute pairwise correlation.
DataFrame.count([axis, level, numeric_only])
Count non-NA cells for each column or row.
DataFrame.cov([min_periods, ddof])
Compute pairwise covariance of columns, excluding NA/null values.
DataFrame.cummax([axis, skipna])
Return cumulative maximum over a DataFrame or Series axis.
DataFrame.cummin([axis, skipna])
Return cumulative minimum over a DataFrame or Series axis.
DataFrame.cumprod([axis, skipna])
Return cumulative product over a DataFrame or Series axis.
DataFrame.cumsum([axis, skipna])
Return cumulative sum over a DataFrame or Series axis.
DataFrame.describe([percentiles, include, ...])
Generate descriptive statistics.
DataFrame.diff([periods, axis])
First discrete difference of element.
DataFrame.eval(expr[, inplace])
Evaluate a string describing operations on DataFrame columns.
DataFrame.kurt([axis, skipna, level, ...])
Return unbiased kurtosis over requested axis.
DataFrame.kurtosis([axis, skipna, level, ...])
Return unbiased kurtosis over requested axis.
DataFrame.mad([axis, skipna, level])
Return the mean absolute deviation of the values over the requested axis.
DataFrame.max([axis, skipna, level, ...])
Return the maximum of the values over the requested axis.
DataFrame.mean([axis, skipna, level, ...])
Return the mean of the values over the requested axis.
DataFrame.median([axis, skipna, level, ...])
Return the median of the values over the requested axis.
DataFrame.min([axis, skipna, level, ...])
Return the minimum of the values over the requested axis.
DataFrame.mode([axis, numeric_only, dropna])
Get the mode(s) of each element along the selected axis.
DataFrame.pct_change([periods, fill_method, ...])
Percentage change between the current and a prior element.
DataFrame.prod([axis, skipna, level, ...])
Return the product of the values over the requested axis.
DataFrame.product([axis, skipna, level, ...])
Return the product of the values over the requested axis.
DataFrame.quantile([q, axis, numeric_only, ...])
Return values at the given quantile over requested axis.
DataFrame.rank([axis, method, numeric_only, ...])
Compute numerical data ranks (1 through n) along axis.
DataFrame.round([decimals])
Round a DataFrame to a variable number of decimal places.
DataFrame.sem([axis, skipna, level, ddof, ...])
Return unbiased standard error of the mean over requested axis.
DataFrame.skew([axis, skipna, level, ...])
Return unbiased skew over requested axis.
DataFrame.sum([axis, skipna, level, ...])
Return the sum of the values over the requested axis.
DataFrame.std([axis, skipna, level, ddof, ...])
Return sample standard deviation over requested axis.
DataFrame.var([axis, skipna, level, ddof, ...])
Return unbiased variance over requested axis.
DataFrame.nunique([axis, dropna])
Count number of distinct elements in specified axis.
DataFrame.value_counts([subset, normalize, ...])
Return a Series containing counts of unique rows in the DataFrame.
DataFrame.add_prefix(prefix)
Prefix labels with string prefix.
DataFrame.add_suffix(suffix)
Suffix labels with string suffix.
DataFrame.align(other[, join, axis, level, ...])
Align two objects on their axes with the specified join method.
DataFrame.at_time(time[, asof, axis])
Select values at particular time of day (e.g., 9:30AM).
DataFrame.between_time(start_time, end_time)
Select values between particular times of the day (e.g., 9:00-9:30 AM).
DataFrame.drop([labels, axis, index, ...])
Drop specified labels from rows or columns.
DataFrame.drop_duplicates([subset, keep, ...])
Return DataFrame with duplicate rows removed.
DataFrame.duplicated([subset, keep])
Return boolean Series denoting duplicate rows.
DataFrame.equals(other)
Test whether two objects contain the same elements.
DataFrame.filter([items, like, regex, axis])
Subset the dataframe rows or columns according to the specified index labels.
DataFrame.first(offset)
Select initial periods of time series data based on a date offset.
DataFrame.head([n])
Return the first n rows.
DataFrame.idxmax([axis, skipna])
Return index of first occurrence of maximum over requested axis.
DataFrame.idxmin([axis, skipna])
Return index of first occurrence of minimum over requested axis.
DataFrame.last(offset)
Select final periods of time series data based on a date offset.
DataFrame.reindex([labels, index, columns, ...])
Conform Series/DataFrame to new index with optional filling logic.
DataFrame.reindex_like(other[, method, ...])
Return an object with matching indices as other object.
DataFrame.rename([mapper, index, columns, ...])
Alter axes labels.
DataFrame.rename_axis([mapper, index, ...])
Set the name of the axis for the index or columns.
DataFrame.reset_index([level, drop, ...])
Reset the index, or a level of it.
DataFrame.sample([n, frac, replace, ...])
Return a random sample of items from an axis of object.
DataFrame.set_axis(labels[, axis, inplace])
Assign desired index to given axis.
DataFrame.set_index(keys[, drop, append, ...])
Set the DataFrame index using existing columns.
DataFrame.tail([n])
Return the last n rows.
DataFrame.take(indices[, axis, is_copy])
Return the elements in the given positional indices along an axis.
DataFrame.truncate([before, after, axis, copy])
Truncate a Series or DataFrame before and after some index value.
DataFrame.backfill([axis, inplace, limit, ...])
Synonym for DataFrame.fillna() with method='bfill'.
DataFrame.bfill([axis, inplace, limit, downcast])
Synonym for DataFrame.fillna() with method='bfill'.
DataFrame.dropna([axis, how, thresh, ...])
Remove missing values.
DataFrame.ffill([axis, inplace, limit, downcast])
Synonym for DataFrame.fillna() with method='ffill'.
DataFrame.fillna([value, method, axis, ...])
Fill NA/NaN values using the specified method.
DataFrame.interpolate([method, axis, limit, ...])
Fill NaN values using an interpolation method.
DataFrame.isna()
Detect missing values.
DataFrame.isnull()
DataFrame.isnull is an alias for DataFrame.isna.
DataFrame.notna()
Detect existing (non-missing) values.
DataFrame.notnull()
DataFrame.notnull is an alias for DataFrame.notna.
DataFrame.pad([axis, inplace, limit, downcast])
Synonym for DataFrame.fillna() with method='ffill'.
DataFrame.replace([to_replace, value, ...])
Replace values given in to_replace with value.
DataFrame.droplevel(level[, axis])
Return Series/DataFrame with requested index / column level(s) removed.
DataFrame.pivot([index, columns, values])
Return reshaped DataFrame organized by given index / column values.
DataFrame.pivot_table([values, index, ...])
Create a spreadsheet-style pivot table as a DataFrame.
DataFrame.reorder_levels(order[, axis])
Rearrange index levels using input order.
DataFrame.sort_values(by[, axis, ascending, ...])
Sort by the values along either axis.
DataFrame.sort_index([axis, level, ...])
Sort object by labels (along an axis).
DataFrame.nlargest(n, columns[, keep])
Return the first n rows ordered by columns in descending order.
DataFrame.nsmallest(n, columns[, keep])
Return the first n rows ordered by columns in ascending order.
DataFrame.swaplevel([i, j, axis])
Swap levels i and j in a MultiIndex.
DataFrame.stack([level, dropna])
Stack the prescribed level(s) from columns to index.
DataFrame.unstack([level, fill_value])
Pivot a level of the (necessarily hierarchical) index labels.
DataFrame.swapaxes(axis1, axis2[, copy])
Interchange axes and swap values axes appropriately.
DataFrame.melt([id_vars, value_vars, ...])
Unpivot a DataFrame from wide to long format, optionally leaving identifiers set.
DataFrame.explode(column[, ignore_index])
Transform each element of a list-like to a row, replicating index values.
DataFrame.squeeze([axis])
Squeeze 1 dimensional axis objects into scalars.
DataFrame.to_xarray()
Return an xarray object from the pandas object.
DataFrame.T
DataFrame.transpose(*args[, copy])
Transpose index and columns.
DataFrame.append(other[, ignore_index, ...])
Append rows of other to the end of caller, returning a new object.
DataFrame.assign(**kwargs)
Assign new columns to a DataFrame.
DataFrame.compare(other[, align_axis, ...])
Compare to another DataFrame and show the differences.
DataFrame.join(other[, on, how, lsuffix, ...])
Join columns of another DataFrame.
DataFrame.merge(right[, how, on, left_on, ...])
Merge DataFrame or named Series objects with a database-style join.
DataFrame.update(other[, join, overwrite, ...])
Modify in place using non-NA values from another DataFrame.
DataFrame.asfreq(freq[, method, how, ...])
Convert time series to specified frequency.
DataFrame.asof(where[, subset])
Return the last row(s) without any NaNs before where.
DataFrame.shift([periods, freq, axis, ...])
Shift index by desired number of periods with an optional time freq.
DataFrame.slice_shift([periods, axis])
(DEPRECATED) Equivalent to shift without copying data.
DataFrame.tshift([periods, freq, axis])
(DEPRECATED) Shift the time index, using the index's frequency if available.
DataFrame.first_valid_index()
Return index for first non-NA value or None, if no NA value is found.
DataFrame.last_valid_index()
Return index for last non-NA value or None, if no NA value is found.
DataFrame.resample(rule[, axis, closed, ...])
Resample time-series data.
DataFrame.to_period([freq, axis, copy])
Convert DataFrame from DatetimeIndex to PeriodIndex.
DataFrame.to_timestamp([freq, how, axis, copy])
Cast to DatetimeIndex of timestamps, at beginning of period.
DataFrame.tz_convert(tz[, axis, level, copy])
Convert tz-aware axis to target time zone.
DataFrame.tz_localize(tz[, axis, level, ...])
Localize tz-naive index of a Series or DataFrame to target time zone.
Flags refer to attributes of the pandas object. Properties of the dataset (like the date is was recorded, the URL it was accessed from, etc.) should be stored in DataFrame.attrs.
Flags(obj, *, allows_duplicate_labels)
Flags that apply to pandas objects.
DataFrame.attrs is a dictionary for storing global metadata for this DataFrame.
Warning
DataFrame.attrs is considered experimental and may change without warning.
DataFrame.attrs
Dictionary of global attributes of this dataset.
DataFrame.plot is both a callable method and a namespace attribute for specific plotting methods of the form DataFrame.plot.<kind>.
DataFrame.plot([x, y, kind, ax, ....])
DataFrame plotting accessor and method
DataFrame.plot.area([x, y])
Draw a stacked area plot.
DataFrame.plot.bar([x, y])
Vertical bar plot.
DataFrame.plot.barh([x, y])
Make a horizontal bar plot.
DataFrame.plot.box([by])
Make a box plot of the DataFrame columns.
DataFrame.plot.density([bw_method, ind])
Generate Kernel Density Estimate plot using Gaussian kernels.
DataFrame.plot.hexbin(x, y[, C, ...])
Generate a hexagonal binning plot.
DataFrame.plot.hist([by, bins])
Draw one histogram of the DataFrame's columns.
DataFrame.plot.kde([bw_method, ind])
Generate Kernel Density Estimate plot using Gaussian kernels.
DataFrame.plot.line([x, y])
Plot Series or DataFrame as lines.
DataFrame.plot.pie(**kwargs)
Generate a pie plot.
DataFrame.plot.scatter(x, y[, s, c])
Create a scatter plot with varying marker point size and color.
DataFrame.boxplot([column, by, ax, ...])
Make a box plot from DataFrame columns.
DataFrame.hist([column, by, grid, ...])
Make a histogram of the DataFrame's columns.
Sparse-dtype specific methods and attributes are provided under the DataFrame.sparse accessor.
DataFrame.sparse.density
Ratio of non-sparse points to total (dense) data points.
DataFrame.sparse.from_spmatrix(data[, ...])
Create a new DataFrame from a scipy sparse matrix.
DataFrame.sparse.to_coo()
Return the contents of the frame as a sparse SciPy COO matrix.
DataFrame.sparse.to_dense()
Convert a DataFrame with sparse values to dense.
DataFrame.from_dict(data[, orient, dtype, ...])
Construct DataFrame from dict of array-like or dicts.
DataFrame.from_records(data[, index, ...])
Convert structured or record ndarray to DataFrame.
DataFrame.to_parquet([path, engine, ...])
Write a DataFrame to the binary parquet format.
DataFrame.to_pickle(path[, compression, ...])
Pickle (serialize) object to file.
DataFrame.to_csv([path_or_buf, sep, na_rep, ...])
Write object to a comma-separated values (csv) file.
DataFrame.to_hdf(path_or_buf, key[, mode, ...])
Write the contained data to an HDF5 file using HDFStore.
DataFrame.to_sql(name, con[, schema, ...])
Write records stored in a DataFrame to a SQL database.
DataFrame.to_dict([orient, into])
Convert the DataFrame to a dictionary.
DataFrame.to_excel(excel_writer[, ...])
Write object to an Excel sheet.
DataFrame.to_json([path_or_buf, orient, ...])
Convert the object to a JSON string.
DataFrame.to_html([buf, columns, col_space, ...])
Render a DataFrame as an HTML table.
DataFrame.to_feather(path, **kwargs)
Write a DataFrame to the binary Feather format.
DataFrame.to_latex([buf, columns, ...])
Render object to a LaTeX tabular, longtable, or nested table.
DataFrame.to_stata(path[, convert_dates, ...])
Export DataFrame object to Stata dta format.
DataFrame.to_gbq(destination_table[, ...])
Write a DataFrame to a Google BigQuery table.
DataFrame.to_records([index, column_dtypes, ...])
Convert DataFrame to a NumPy record array.
DataFrame.to_string([buf, columns, ...])
Render a DataFrame to a console-friendly tabular output.
DataFrame.to_clipboard([excel, sep])
Copy object to the system clipboard.
DataFrame.to_markdown([buf, mode, index, ...])
Print DataFrame in Markdown-friendly format.
DataFrame.style
Returns a Styler object.


These are primarily intended for library authors looking to extend pandas objects.
api.extensions.register_extension_dtype(cls)
Register an ExtensionType with pandas as class decorator.
api.extensions.register_dataframe_accessor(name)
Register a custom accessor on DataFrame objects.
api.extensions.register_series_accessor(name)
Register a custom accessor on Series objects.
api.extensions.register_index_accessor(name)
Register a custom accessor on Index objects.
api.extensions.ExtensionDtype()
A custom data type, to be paired with an ExtensionArray.
api.extensions.ExtensionArray()
Abstract base class for custom 1-D array types.
arrays.PandasArray(values[, copy])
A pandas ExtensionArray for NumPy data.
Additionally, we have some utility methods for ensuring your object behaves correctly.
api.indexers.check_array_indexer(array, indexer)
Check if indexer is a valid array indexer for array.
The sentinel pandas.api.extensions.no_default is used as the default value in some methods. Use an is comparison to check if the user provides a non-default value.