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.
Unlike agg, apply’s callable is passed a sub-DataFrame which gives you access to all the columns
In [104]: df=pd.DataFrame( .....: { .....: "animal":"cat dog cat fish dog cat cat".split(), .....: "size":list("SSMMMLL"), .....: "weight":[8,10,11,1,20,12,12], .....: "adult":[False]*5+[True]*2, .....: } .....: ) .....: In [105]: dfOut[105]: animal size weight adult0 cat S 8 False1 dog S 10 False2 cat M 11 False3 fish M 1 False4 dog M 20 False5 cat L 12 True6 cat L 12 True# List the size of the animals with the highest weight.In [106]: df.groupby("animal").apply(lambdasubf:subf["size"][subf["weight"].idxmax()],include_groups=False)Out[106]: animalcat Ldog Mfish Mdtype: object
In [107]: gb=df.groupby("animal")In [108]: gb.get_group("cat")Out[108]: animal size weight adult0 cat S 8 False2 cat M 11 False5 cat L 12 True6 cat L 12 True
In [131]: df=pd.DataFrame( .....: {"Color":"Red Red Red Blue".split(),"Value":[100,150,50,50]} .....: ) .....: In [132]: dfOut[132]: Color Value0 Red 1001 Red 1502 Red 50
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
Reading multiple files to create a single DataFrame
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():
In [189]: foriinrange(3): .....: data=pd.DataFrame(np.random.randn(10,4
Parsing date components in multi-columns
Parsing date components in multi-columns is faster with a format
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
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 gccmain.c-std=gnu99 on a
64-bit machine,
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:
In [215]: df=pd.DataFrame(np.random.random(size=(100,5)))In [216]: corr_mat=df.corr()In [217]: mask=np.tril(np.ones_like(corr_mat,dtype=np.bool_),k=-1)In [218]: corr_mat.where(mask)Out[218]: 0 1 2 3 40 NaN NaN NaN NaN NaN1 -0.079861 NaN NaN NaN NaN2 -0.236573 0.183801 NaN NaN NaN3 -0.013795 -0.051975 0.037235 NaN NaN4 -0.031974 0.118342 -0.073499 -0.02063 NaN
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.
In [219]: defdistcorr(x,y): .....: n=len(x) .....: a=np.zeros(shape=(n,n)) .....: b=np.zeros(
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:
To assess if a series has a constant value, we can check if series.nunique()<=1.
However, a more performant approach, that does not count all unique values first, is:
In [244]: v=s.to_numpy()In [245]: is_constant=v.shape[0]==0or(s[0]==s).all()
This approach assumes that the series does not contain missing values.
For the case that we would drop NA values, we can simply remove those values first:
In [246]: v=s.dropna().to_numpy()In [247]: is_constant=v.shape[0]==0or(s[0]==s).all()
If missing values are considered distinct from any other value, then one could use:
In [248]: v=s.to_numpy()In [249]: is_constant=v.shape[0]==0or(s[0]==s).all()ornotpd.notna(v)
(Note that this example does not disambiguate between np.nan, pd.NA and None)
In [85]: importitertoolsIn [86]: index=list(itertools.product(["Ada","Quinn","Violet"],["Comp","Math","Sci"]))In [87]: headr=list(itertools.product(["Exams","Labs"],["I","II"]))In [88]: indx=pd.MultiIndex.from_tuples(index,names=["Student","Course"])In [89]: cols=pd.MultiIndex.from_tuples(headr)# Notice these are un-namedIn [90]: data=[[70+x+y+(x*y)%3forxinrange(4)]foryinrange(9)]In [91]: df=pd.DataFrame(data,indx,cols)In [92]: dfOut[92]: Exams Labs I II I IIStudent Course Ada Comp 70 71 72 73 Math 71 73 75 74 Sci 72 75 75 75Quinn Comp 73 74 75 76 Math 74 76 78 77 Sci 75 78 78 78Violet Comp 76 77 78 79 Math 77 79 81 80 Sci 78 81 81 81In [93]: All=slice(None)In [94]: df.loc["Violet"]Out[94]: Exams Labs I II I IICourse Comp 76 77 78 79Math 77 79 81 80Sci 78 81 81 81In [95]: df.loc[(All,"Math"),All]Out[95]: Exams Labs I II I IIStudent Course Ada Math 71 73 75 74Quinn Math 74 76 78 77Violet Math 77 79 81 80In [96]: df.loc[(slice("Ada","Quinn"),"Math"),All]Out[96]: Exams Labs I II I IIStudent Course Ada Math 71 73 75 74Quinn Math 74 76 78 77In [97]: df.loc[(All,"Math"),("Exams")]Out[97]: I IIStudent Course Ada Math 71 73Quinn Math 74 76Violet Math 77 79In [98]: df.loc[(All,"Math"),(All,"II")]Out[98]: Exams Labs II IIStudent Course Ada Math 73 74Quinn Math 76 77Violet Math 79 80
In [206]: df=pd.DataFrame(np.random.randn(8,3))In [207]: store=pd.HDFStore("test.h5")In [208]: store.put("df",df)# you can store an arbitrary Python object via pickleIn [209]: store.get_storer("df").attrs.my_attribute={"A":10}In [210]: store.get_storer("df").attrs.my_attributeOut[210]: {'A': 10}
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.
In [211]: store=pd.HDFStore("test.h5","w",driver="H5FD_CORE")In [212]: df=pd.DataFrame(np.random.randn(8,3))In [213]: store["test"]=df# only after closing the store, data is written to disk:In [214]: store.close()
;
}
Data
;
int
main
(
int
argc
,
const
char
*
argv
[])
{
size_t
n
=
10
;
Data
d
[
n
];
for
(
int
i
=
0
;
i
<
n
;
++
i
)
{
d
[
i
].
count
=
i
;
d
[
i
].
avg
=
i
+
1.0
;
d
[
i
].
scale
=
(
float
)
i
+
2.0f
;
}
FILE
*
file
=
fopen
(
"binary.dat"
,
"wb"
);
fwrite
(
&
d
,
sizeof
(
Data
),
n
,
file
);
fclose
(
file
);
return
0
;
}
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:
names="count","avg","scale"# note that the offsets are larger than the size of the type because of# struct paddingoffsets=0,8,16formats="i4","f8","f4"dt=np.dtype({"names":names,"offsets":offsets,"formats":formats},align=True)df=pd.DataFrame(np.fromfile("binary.dat",dt))