set_index(self, keys, drop=True, append=False, inplace=False, verify_integrity=False)
Set the DataFrame index using existing columns.
Set the DataFrame index (row labels) using one or more existing
columns or arrays (of the correct length). The index can replace the
existing index or expand on it.
参数详解:
DataFrame or None
Changed row labels or None if inplace=True
.
See Also
df = pd.DataFrame({‘month’: [1, 4, 7, 10],
… ‘year’: [2012, 2014, 2013, 2014],
… ‘sale’: [55, 40, 84, 31]})
df
month year sale
0 1 2012 55
1 4 2014 40
2 7 2013 84
3 10 2014 31
Set the index to become the ‘month’ column:
df.set_index(‘month’)
year sale
month
1 2012 55
4 2014 40
7 2013 84
10 2014 31
Create a MultiIndex using columns ‘year’ and ‘month’:
df.set_index([‘year’, ‘month’])
sale
year month
2012 1 55
2014 4 40
2013 7 84
2014 10 31
Create a MultiIndex using an Index and a column:
df.set_index([pd.Index([1, 2, 3, 4]), ‘year’])
month sale
year
1 2012 1 55
2 2014 4 40
3 2013 7 84
4 2014 10 31
Create a MultiIndex using two Series:
s = pd.Series([1, 2, 3, 4])
df.set_index([s, s**2])
month year sale
1 1 1 2012 55
2 4 4 2014 40
3 9 7 2013 84
4 16 10 2014 31Original: https://blog.csdn.net/c_lanxiaofang/article/details/125773853
Author: 懒笑翻
Title: df.set_index()
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/753069/
转载文章受原作者版权保护。转载请注明原作者出处!