วิธีการเปลี่ยนแปลง indeces ใน pandas dataframe
>>> df.set_index('month')
year sale
month
1 2012 55
4 2014 40
7 2013 84
10 2014 31
reset_index pandas
df.reset_index(drop=True, inplace=True)
ตั้งดัชนีต้องคอลัมน์ pandas
# method A
df = df.set_index('col')
# method B
df['col'] = df.index
วิธีการเปลี่ยนแปลงดัชนีใน dataframe เป็นภาษาไพธอน
index = [1,2]
df.index = index
pandas สร้างคอลัมน์จากดัชนี
df.reset_index(level=0, inplace=True)
ยังไงตั้งดัชนี pandas
# assignment copy
df = df.set_index('month')
# or inplace
df.set_index('month', inplace=True)
# year sale month month year sale
# 0 2012 55 1 1 2012 55
# 1 2014 40 4 => 4 2014 40
# 2 2013 84 7 7 2013 84
# 3 2014 31 10 10 2014 31
ตั้งดัชนีใน datarame
df = df.set_index('col')
ยังไงตั้งดัชนี pandas
# assignment copy
df = df.set_index('month')
# or inplace
df.set_index('month', inplace=True)
# year sale month month year sale
# 0 2012 55 1 1 2012 55
# 1 2014 40 4 => 4 2014 40
# 2 2013 84 7 7 2013 84
# 3 2014 31 10 10 2014 31
เพิ่มเป็นดัชนีคอลัมน์ pandas
import numpy as np
import pandas as pd
df = pd.DataFrame({'month': [2, 5, 8, 10],
'year': [2017, 2019, 2018, 2019],
'sale': [60, 45, 90, 36]})
df.set_index('month')
pandas df ให้ตั้งดัชนีคอลัมน์
df.reset_index(inplace=True)
df = df.rename(columns = {'index':'new column name'})
ยังไงตั้งดัชนี pandas
# assignment copy
df = df.set_index('month')
# or inplace
df.set_index('month', inplace=True)
# year sale month month year sale
# 0 2012 55 1 1 2012 55
# 1 2014 40 4 => 4 2014 40
# 2 2013 84 7 7 2013 84
# 3 2014 31 10 10 2014 31
str แทนที่ pandas
>>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f.', 'ba', regex=True)
0 bao
1 baz
2 NaN
dtype: object