Sie sind auf Seite 1von 6

OS functions

import os

os.system() Executing a shell command


os.environ() Get the users environment
os.getcwd() Returns the current working
directory
os.getgid() Return the real group id of the current
process.
os.getuid() Return the current process’s user id.
os.getpid() Returns the real process ID of the
current process.
os.umask(mask) Set the current numeric umask and return
the
previous umask.
os.uname() Return information identifying the
current operating
system.
os.chroot(path) Change the root directory of the current
process
to path.
os.listdir(path) Return a list of the entries in the directory
given
by path
os.mkdir(path) Create a directory named path with
numeric
mode mode
os.makedirs(path) Recursive directory creation function.
os.remove(path) Remove (delete) the file path.
os.removedirs(path) Remove directories recursively.
os.rename(src, dst) Rename the file or directory src to
dst.
os.chdir(path) Modify the directory path.
os.rmdir(path) Remove (delete) the directory path.

NumPy
The NumPy library is the core library for scientific computing in Python. It provides a high-
performance multidimensional array object, and tools for working with these arrays.

a = np.array([1,2,3])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)

c = np.array([[(1.5,2,3), (4,5,6)], [(3,2,1), (4,5,6)]], dtype = float)

np.zeros((3,4)) Create an array of zeros


np.ones((2,3,4),dtype=np.int16) Create an array of ones
d = np.arange(10,25,5) Create an array of evenly spaced values (step value)
np.linspace(0,2,9) Create an array of evenly spaced values (number of
samples)
e = np.full((2,2),7) Create a constant array
f = np.eye(2) Create a 2X2 identity matrix
np.random.random((2,2)) Create an array with random values
np.empty((3,2)) Create an empty array

a.shape Array dimensions


len(a) Length of array
b.ndim Number of array dimensions
e.size Number of array elements
b.dtype Data type of array elements
b.dtype.name Name of data type
b.astype(int) Convert an array to a different type

i = np.transpose(b) Permute array dimensions


i.T Permute array dimensions Changing Array Shape
b.ravel() Flatten the array
g.reshape(3,-2) Reshape, but don’t change data Adding/Removing Elements
h.resize((2,6)) Return a new array with shape (2,6)
np.append(h,g) Append items to an array
np.insert(a, 1, 5) Insert items in an array
np.delete(a,[1]) Delete items from an array

Pandas
The Pandas library is built on NumPy and provides easy-to-use data structures and data analysis
tools for the Python programming language.
import pandas as pd
s = pd.Series([3, -5, 7, 4], index=['a', 'b', 'c', 'd'])

data = {'Country': ['Belgium', 'India', 'Brazil'], 'Capital': ['Brussels', 'New Delhi', 'Brasília'], 'Population':
[11190846, 1303171035, 207847528]}
df = pd.DataFrame(data, columns=['Country', 'Capital', 'Population'])
Read and Write
pd.read_csv('file.csv', header=None, nrows=5)
df.to_csv('myDataFrame.csv') Read and Write to Excel
pd.read_excel('file.xlsx')
pd.to_excel('dir/myDataFrame.xlsx', sheet_name='Sheet1') Read multiple sheets from the same file
xlsx = pd.ExcelFile('file.xls')
df = pd.read_excel(xlsx, 'Sheet1')

Selecting, Boolean Indexing & Setting


df.iloc[[0],[0]] Select single value by row & column
df.iat([0],[0]) By Label
df.loc[[0], ['Country']] Select single value by row & column labels
df.at([0], ['Country']) By Label/Position
df.ix[2] Select single row of subset of rows
df.ix[:,'Capital'] Select a single column of subset of columns
df.ix[1,'Capital'] Select rows and columns

s.drop(['a', 'c']) Drop values from rows (axis=0)


df.drop('Country', axis=1) Drop values from columns(axis=1)

df.sort_index() Sort by labels along an axis


df.sort_values(by='Country') Sort by the values along an axis
df.rank() Assign ranks to entries
df.shape (rows,columns)
df.index Describe index
df.columns Describe DataFrame columns
df.info() Info on DataFrame
df.count() Number of non-NA values

df.sum() Sum of values


df.cumsum() Cummulative sum of values
df.min()/df.max() Minimum/maximum values
df.idxmin()/df.idxmax() Minimum/Maximum index value
df.describe() Summary statistics
df.mean() Mean of values
df.median() Median of values

f = lambda x: x*2 Anonymous Function


df.apply(f) Apply function
df.applymap(f) Apply function element-wise

Dunder Methods:

init
__init__(self, ...)
Class.__init__(...) <==> x.__init__(...) <==> Class(...)
Called when class is called, or in other words when you instantiate the class.
Shouldn't return any value; the created instance will be returned automatically.

Represention
__call__(self, ...)
x.__call__(...) <==> x(...)
Called when instance is called.
__del__(self)
Called when instance is about to be destroyed.
__repr__(self)
x.__repr__() <==> repr(x) <==> `x`
Should return a string representation of the class or instance with as much
information as possible,
__str__(self)
x.__str__() <==> str(x) <==> print x
Should return an informal, user-friendly string describing the class or instance.
Return value must be a string.
__unicode__(self)
x.__unicode__() <==> unicode(x)
Should return an informal, user-friendly unicode string describing the class or
instance.

Boolean
__nonzero__(self)
bool(x) <==> x.__nonzero__()
Called by the built-in function bool, or whenever any truth-value test occurs.

Compare
__cmp__(self, other)
x.__cmp__(other) <==> cmp(x, other)
Should return a negative integer if instance is less than other, 0 if instance
is equal to other, or a positive integer if instance is greater than other.
__eq__(self, other)
x.__eq__(other) <==> x == other
Must be implemented if two instances are to be perceived as identical,
__ne__(self, other)
x.__ne__(other) <==> x != other
Should return a value indicating if instance is not equal to other.

Math
__add__(self, other)
x.__add__(other) <==> x + other
If not defined or returns NotImplemented, other.__radd__(x) is tried.
__div__(self, other)
x.__div__(other) <==> x / other
If from __future__ import division is used, __truediv__ is called instead.
If not defined or returns NotImplemented, other.__rdiv__(x) is tried.

__truediv__(self, other)
x.__truediv__(other) <==> x / other
Only called if from __future__ import division is used. Otherwise, __div__ is used.
If not defined or returns NotImplemented, other.__rtruediv__(x) is tried.

__floordiv__(self, other)
x.__floordiv__(other) <==> x // other
If not defined or returns NotImplemented, other.__rfloordiv__(x) is tried.

__mod__(self, other)
x.__mod__(other) <==> x % other
If not defined or returns NotImplemented, other.__rmod__(x) is tried.

__divmod__(self, other)
x.__divmod__(other) <==> divmod(x, other)
Should be equivelant to using __floordiv__ and __mod__. Should not be related
to __truediv__.
If not defined or returns NotImplemented, other.__rdivmod__(x) is tried.

__pow__(self, other [, mod])


x.__pow__(other [, mod]) <==> x ** other [% mod] <==> pow(x, other [, mod])
__xor__(self, other)
x.__xor__(other) <==> x ^ other
If not defined or returns NotImplemented, other.__rxor__(x) is tried.
__abs__(self)
x.__abs__() <==> abs(x)
If not defined, the abs function cannot be used on this instance and
an AttributeError is raised.
Datatype

__int__(self)
x.__int__() <==> int(x)
Should return a integer representation of x, as an int instance.
__index__(self)
other[x.__index__()] <==> other[x]
x.__index()__ <==> operator.index(x)

Structural
__len__(self)
x.__len__() <==> len(x)
__contains__(self, item)
x.__contains__(item) <==> item in x
__iter__(self)
x.__iter__() <==> iter(x)
__reversed__(self)
x.__reversed__() <==> reversed(x)
__getitem__(self, key)
x.__getitem__(key) <==> x[key]
__setitem__(self, key, value)
x.__setitem__(key, value) <==> x[key] = value
__delitem__(self, key)
x.__delitem__(key) <==> del x[key]

Slicing
__getslice__(self, start, end)
x.__getslice__(start, end) <==> x[start:end]
__setslice__(self, start, end, sequence)
x.__setitem__(start, end, sequence) <==> x[start:end] = sequence
__delslice__(self, key)
x.__delslice__(start, end) <==> del x[start:end]

Attribute
__get__(self, instance, owner)
x.__get__(self, container, Container) <==> container.x
x.__get__(self, None, Container) <==> Container.x
Called when attribute lookup is attempted in a new-style instance or class.
__set__(self, instance, value)
x.__set__(self, container, value) <==> container.x = value
Called when attribute assignment is attempted in a new-style instance.
__delete__(self, instance)
x.__delete__(self, container) <==> del container.x
Called when attribute deletion is attempted in a new-style instance.

Copying
__copy__ , __deepcopy__

"With" Statements
__enter__ , __exit__

Das könnte Ihnen auch gefallen