首先創(chuàng)建一個(gè)DataFrame
>>> import pandas as pd
>>> df= pd.DataFrame({
'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Yum Yum'],
'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
'rating': [4, 4, 3.5, 15, 5]
})
>>> df
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Yum Yum pack 5.0
來(lái)到賦值場(chǎng)景:
- 需求:需要對(duì) rating 列的[0, 1, 4]行的3個(gè)元素賦值為[[5], [5], [4]]躏尉, 也就是同時(shí)使用位置索引(positional indexing)和標(biāo)簽索引(label-based indexing)
- 官方建議的操作為:
>>> import numpy as np
>>> df.loc[df.index[[0, 1, 4]], 'rating'] = np.array([5, 5, 4]).reshape((3, 1))
>>> df
brand style rating
0 Yum Yum cup 5.0
1 Yum Yum cup 5.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Yum Yum pack 4.0
>>> #或者
>>> df.iloc[[0, 1, 4], df.columns.get_loc('rating')] = np.array([5, 5, 4]).reshape((3, 1))
>>> df
brand style rating
0 Yum Yum cup 5.0
1 Yum Yum cup 5.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Yum Yum pack 4.0
>>>#或者
>>> df.iloc[df.index[[0, 1, 4]], df.columns.get_loc('rating')] = np.array([5, 5, 4]).reshape((3, 1))
>>> df
brand style rating
0 Yum Yum cup 5.0
1 Yum Yum cup 5.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Yum Yum pack 4.0
>>>#或者,使用.get_indexer()可以同時(shí)索引多列如.get_indexer(['style', 'rating'])
>>> df.iloc[df.index[[0, 1, 4]], df.columns.get_indexer(['rating'])] = np.array([4, 4, 5]).reshape((3, 1))
>>> df
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Yum Yum pack 5.0