Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Ctrl+K

pandas.DataFrame.set_index#

DataFrame.set_index(keys,*,drop=True,append=False,inplace=False,verify_integrity=False)[source]#

Set the DataFrame index using existing columns.

Set the DataFrame index (row labels) using one or more existingcolumns or arrays (of the correct length). The index can replace theexisting index or expand on it.

Parameters:
keyslabel or array-like or list of labels/arrays

This parameter can be either a single column key, a single array ofthe same length as the calling DataFrame, or a list containing anarbitrary combination of column keys and arrays. Here, “array”encompassesSeries,Index,np.ndarray, andinstances ofIterator.

dropbool, default True

Delete columns to be used as the new index.

appendbool, default False

Whether to append columns to existing index.

inplacebool, default False

Whether to modify the DataFrame rather than creating a new one.

verify_integritybool, default False

Check the new index for duplicates. Otherwise defer the check untilnecessary. Setting to False will improve the performance of thismethod.

Returns:
DataFrame or None

Changed row labels or None ifinplace=True.

See also

DataFrame.reset_index

Opposite of set_index.

DataFrame.reindex

Change to new indices or expand indices.

DataFrame.reindex_like

Change to same indices as other DataFrame.

Examples

>>>df=pd.DataFrame({'month':[1,4,7,10],...'year':[2012,2014,2013,2014],...'sale':[55,40,84,31]})>>>df   month  year  sale0      1  2012    551      4  2014    402      7  2013    843     10  2014    31

Set the index to become the ‘month’ column:

>>>df.set_index('month')       year  salemonth1      2012    554      2014    407      2013    8410     2014    31

Create a MultiIndex using columns ‘year’ and ‘month’:

>>>df.set_index(['year','month'])            saleyear  month2012  1     552014  4     402013  7     842014  10    31

Create a MultiIndex using an Index and a column:

>>>df.set_index([pd.Index([1,2,3,4]),'year'])         month  sale   year1  2012  1      552  2014  4      403  2013  7      844  2014  10     31

Create a MultiIndex using two Series:

>>>s=pd.Series([1,2,3,4])>>>df.set_index([s,s**2])      month  year  sale1 1       1  2012    552 4       4  2014    403 9       7  2013    844 16     10  2014    31

[8]ページ先頭

©2009-2025 Movatter.jp