http://blog.csdn.net/pipisorry/article/details/18012125
Many of these methods or variants thereof are available on the objectsthat contain an index (Series/Dataframe) and those should most likely beused before calling these methods directly.
(如果索引是從0開始的連續(xù)值,那就是行號了)
nodes_id_index = pd.Index(nodes_series)print(nodes_id_index.get_loc('u_3223_4017'))[Find element's index in pandas Series]
更多請參考[Index]
和Series一樣,在DataFrame中的一列可以通過字典記法或?qū)傩詠頇z索,返回Series:
Note: 返回的Series包含和DataFrame相同的索引,并它們的 name 屬性也被正確的設(shè)置了。
dataframe選擇多列
lines = lines[[0, 1, 4]]或者
lines = lines[['user', 'check-in_time', 'location_id']]
>>> dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
>>> dates
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
'2013-01-05', '2013-01-06'],
dtype='datetime64[ns]', freq='D')
>>> df
A B C D
2013-01-01 2.036209 1.354010 -0.677409 -0.331978
2013-01-02 -1.403797 -1.094992 0.304359 -1.576272
2013-01-03 1.137673 0.636973 -0.746928 -0.606468
2013-01-04 0.833169 -2.575147 0.866364 1.337163
2013-01-05 2.081578 0.489227 -1.340284 -1.043864
2013-01-06 0.042469 -0.426114 -0.026990 0.636364
行可以直接通過[]選擇,只是必須是數(shù)字范圍或者字符串范圍索引:
>>> df['2013-01-02':'2013-01-03']
A B C D
2013-01-02 -1.403797 -1.094992 0.304359 -1.576272
2013-01-03 1.137673 0.636973 -0.746928 -0.606468
>>> df[3:5]
A B C D
2013-01-04 0.833169 -2.575147 0.866364 1.337163
2013-01-05 2.081578 0.489227 -1.340284 -1.043864
行也可以使用一些方法通過位置num或名字label來檢索,例如 ix索引成員(field){更多ix使用實(shí)例可參考后面的“索引,挑選和過濾”部分}。
Note: 提取特定的某列數(shù)據(jù)。Python中,可以使用iloc或者ix屬性,但是ix更穩(wěn)定一些。
In [45]: frame2.ix['three']year 2002state Ohiopop 3.6debt NaNName: three
df.ix[3]
A -0.976627
B 0.766333
C -1.043501
D 0.554586
Name: 2013-01-04 00:00:00, dtype: float64
假設(shè)我們需數(shù)據(jù)第一列的前5行:
df.ix[1:3, ['A', 'B', 'C']]
2013-01-02 -1.403797 -1.094992 0.304359
2013-01-03 1.137673 0.636973 -0.746928
Select via the position of the passed integers
與ix, [], at的區(qū)別是,iloc[3]選擇是的數(shù)據(jù)第3行,而其它如ix[3]選擇的是索引為3的那一行!
In [32]: df.iloc[3]A 0.721555B -0.706771C -1.039575D 0.271860Name: 2013-01-04 00:00:00, dtype: float64
By integer slices, acting similar to numpy/python
In [33]: df.iloc[3:5,0:2] A B2013-01-04 0.721555 -0.7067712013-01-05 -0.424972 0.567020
By lists of integer position locations, similar to the numpy/python style
In [34]: df.iloc[[1,2,4],[0,2]] A C2013-01-02 1.212112 0.1192092013-01-03 -0.861849 -0.4949292013-01-05 -0.424972 0.276232
For getting fast access to a scalar (equiv to the prior method)
In [38]: df.iat[1,1]Out[38]: -0.17321464905330858
In [26]: df.loc[dates[0]]A 0.469112B -0.282863C -1.509059D -1.135632Name: 2013-01-01 00:00:00, dtype: float64
Selecting on a multi-axis by label
In [27]: df.loc[:,['A','B']] A B2013-01-01 0.469112 -0.2828632013-01-02 1.212112 -0.1732152013-01-03 -0.861849 -2.1045692013-01-04 0.721555 -0.7067712013-01-05 -0.424972 0.5670202013-01-06 -0.673690 0.113648
For getting fast access to a scalar (equiv to the prior method)
In [31]: df.at[dates[0],'A']Out[31]: 0.46911229990718628
Using a single column’s values to select data.
In [39]: df[df.A > 0] A B C D2013-01-01 0.469112 -0.282863 -1.509059 -1.1356322013-01-02 1.212112 -0.173215 0.119209 -1.0442362013-01-04 0.721555 -0.706771 -1.039575 0.271860
A where operation for getting.
In [40]: df[df > 0] A B C D2013-01-01 0.469112 NaN NaN NaN...
Using the isin() method for filtering:
In [41]: df2 = df.copy()In [42]: df2['E'] = ['one', 'one','two','three','four','three']In [43]: df2 A B C D E2013-01-01 0.469112 -0.282863 -1.509059 -1.135632 one2013-01-02 1.212112 -0.173215 0.119209 -1.044236 one2013-01-03 -0.861849 -2.104569 -0.494929 1.071804 two2013-01-04 0.721555 -0.706771 -1.039575 0.271860 three2013-01-05 -0.424972 0.567020 0.276232 -1.087401 four2013-01-06 -0.673690 0.113648 -1.478427 0.524988 threeIn [44]: df2[df2['E'].isin(['two','four'])]Out[44]: A B C D E2013-01-03 -0.861849 -2.104569 -0.494929 1.071804 two2013-01-05 -0.424972 0.567020 0.276232 -1.087401 four
Series索引( obj[...] )的工作原理類似與NumPy索引,除了可以使用Series的索引值,也可以僅使用整數(shù)索引。
In [102]: obj = Series(np.arange(4.), index=['a', 'b', 'c', 'd'])In [103]: obj['b'] In [104]: obj[1]Out[103]: 1.0 Out[104]: 1.0In [105]: obj[2:4] In [106]: obj[['b', 'a', 'd']]Out[105]: Out[106]:c 2 b 1d 3 a 0d 3In [107]: obj[[1, 3]] In [108]: obj[obj < 2]b 1 a 0d 3 b 1
整數(shù)索引
操作由整數(shù)索引的pandas對象跟內(nèi)置的Python數(shù)據(jù)結(jié)構(gòu) (如列表和元組)在索引語義上有些不同。
例如,你可能認(rèn)為下面這段代碼不會(huì)產(chǎn)生一個(gè)錯(cuò)誤:
ser = pd.Series(np.arange(3.))
ser
Out[11]:
0 0.0
1 1.0
2 2.0
dtype: float64
ser[-1]
這里,有一個(gè)含有0,1,2的索引,很難推斷出用戶想要什么(基于標(biāo)簽或位置的索引);相反,一個(gè)非整數(shù)索引,就沒有這樣的歧義:
>>>ser2 = pd.Series(np.arange(3.), index=['a', 'b', 'c'])
>>>ser2[-1]
2.0
為了保持良好的一致性,如果軸索引含有索引器,那么根據(jù)整數(shù)進(jìn)行數(shù)據(jù)選取的操作將總是面向標(biāo)簽的。這也包括用ix進(jìn)行切片:
ser.ix[:1]
Out[15]:
0 0.0
1 1.0
dtype: float64
如果你需要可靠的、不考慮索引類型的、基于位置的索引,可以使用Series的iget_ value 方法和 DataFrame 的 irow 和 icol 方法:
>>> ser3 = pd.Series(range(3), index=[-5, 1, 3])
>>> ser3.iget_value(2)
2
>>> frame = pd.DataFrame(np.arange(6).reshape(3, 2), index=[2,0,1])
frame
Out[21]:
0 1
2 0 1
0 2 3
1 4 5
>>> frame.irow(0)
0 0
1 1
Name: 2, dtype: int32
使用標(biāo)簽來切片和正常的Python切片并不一樣,它會(huì)把結(jié)束點(diǎn)也包括在內(nèi):
In [109]: obj['b':'c']b 1c 2
使用這些函數(shù)來賦值
In [110]: obj['b':'c'] = 5In [111]: obja 0b 5c 5d 3
通過切片或一個(gè)布爾數(shù)組來選擇行,這旨在在這種情況下使得DataFrame的語法更像一個(gè)ndarry。
In [116]: data[:2] In [117]: data[data['three'] > 5] one two three four one two three fourOhio 0 1 2 3 Colorado 4 5 6 7Colorado 4 5 6 7 Utah 8 9 10 11 New York 12 13 14 15
DataFrame可以在行上進(jìn)行標(biāo)簽索引,使你可以從DataFrame選擇一個(gè)行和列的子集,使用像NumPy的記法再加上軸標(biāo)簽。這也是一種不是很冗長的重新索引的方法:
因此,有很多方法來選擇和重排包含在pandas對象中的數(shù)據(jù)。
還有分層索引及一些額外的選項(xiàng)。
obj[val] | 從DataFrame選擇單一列或連續(xù)列。特殊情況下的便利:布爾數(shù)組(過濾行),切片(行切片),或布爾DataFrame(根據(jù)一些標(biāo)準(zhǔn)來設(shè)置值)。 |
---|---|
obj.ix[val] | 從DataFrame的行集選擇單行 |
obj.ix[:, val] | 從列集選擇單列 |
obj.ix[val1, val2] | 選擇行和列 |
reindex 方法 | 轉(zhuǎn)換一個(gè)或多個(gè)軸到新的索引 |
xs 方法 | 通過標(biāo)簽選擇單行或單列到一個(gè)Series |
icol, irow 方法 | 通過整數(shù)位置,分別的選擇單行或單列到一個(gè)Series |
get_value, set_value 方法 | 通過行和列標(biāo)選擇一個(gè)單值 |
Note:在設(shè)計(jì)pandas時(shí),我覺得不得不敲下 frame[:, col] 來選擇一列,是非常冗余的(且易出錯(cuò)的),因此列選擇是最常見的操作之一。因此,我做了這個(gè)設(shè)計(jì)權(quán)衡,把所有的富標(biāo)簽索引引入到ix 。
[Different Choices for Indexing]
方法 說明
isin 計(jì)算一個(gè)表示“Series各值是否包含于傳入的值序列中”的布爾型數(shù)組
unique 計(jì)算Series中的唯一值數(shù)組,按發(fā)現(xiàn)的順序返回
value_counts 返回一個(gè)Series,其索引為唯一值,其值為頻率,按計(jì)數(shù)值降序排列
這類方法可以從一維Series的值中抽取信息。
用于判斷矢量化集合的成員資格,可用于選取Series中或DataFrame列中 數(shù)據(jù)的子集:
>>> obj
0 c
1 a
2 d
3 a
4 a
5 b
6 b
7 c
8 c
dtype: object
>>>mask=obj.isin(['b','c'])
>>> mask
0 True...
8 True
dtype: bool
>>> obj[mask]
0 c
5 b
6 b
7 c
8 c
>>> obj=Series(['c','a','d','a','a','b','b','c','c'])
# 函數(shù)是unique,它可以得到Series中的唯一值數(shù)組:
>>>uniques = obj.unique()
>>>uniques
array(['c', 'a', 'd', 'b'], dtype=object)
返冋的唯一值是未排序的,如果需要的話,可以對結(jié)果再次進(jìn)行排序(uniques. sort())。
用于計(jì)算一個(gè)Series中各值出現(xiàn)的頻率:
>>> obj.value_counts()
c 3
a 3
b 2
d 1
dtype: int64
為了便于査看,結(jié)果Series是按值頻率降序排列的。
查源碼,發(fā)現(xiàn)這個(gè)統(tǒng)計(jì)是通過hashtable實(shí)現(xiàn)的。keys, counts = htable.value_count_scalar64(values, dropna)
value_counts還是一個(gè)頂級pandas方法,可用于任何數(shù)組或序列:
>>> pd.value_counts(obj.values, sort=False)
a 3
c 3
b 2
d 1
dtype: int64
返回一個(gè)pandas.series對象,不過你基本可以將它當(dāng)成dict一樣使用。
當(dāng)然也可以減去一些判斷,直接使用pandas.value_counts()調(diào)用的hashtable統(tǒng)計(jì)方法(lz在源碼中看到的)
import pandas.hashtable as htablevalues = np.array([1, 2, 3, 5, 1, 3, 3, 2, 3, 5])values_cnts = dict(zip(*htable.value_count_scalar64(values, dropna=True)))print(values_cnts)
有時(shí),可能希望得到DataFrame中多個(gè)相關(guān)列的一張柱狀圖。例如:
>>>data = pd.DataFrame({'Qu1': [1, 3, 4, 3, 4],'Qu2': [2, 3, 1, 2, 3],'Qu3': [1, 5, 2, 4, 4]})
>>>data
Qu1 Qu2 Qu3
0 1 2 1
1 3 3 5
2 4 1 2
3 3 2 4
4 4 3 4
將 pandas.value_counts 傳給該 DataFrame 的 apply 函數(shù):
In[25]: data.apply(pd.value_counts).fillna(0)
Qu1 Qu2 Qu3
1 1.0 1.0 1.0
2 0.0 2.0 1.0
3 2.0 2.0 0.0
4 2.0 0.0 2.0
5 0.0 0.0 1.0
pandas的索引對象用來保存坐標(biāo)軸標(biāo)簽和其它元數(shù)據(jù)(如坐標(biāo)軸名或名稱)。構(gòu)建一個(gè)Series或DataFrame時(shí)任何數(shù)組或其它序列標(biāo)簽在內(nèi)部轉(zhuǎn)化為索引:
In [68]: obj = Series(range(3), index=['a', 'b', 'c'])In [69]: index = obj.indexIn [70]: indexOut[70]: Index([a, b, c], dtype=object)In [71]: index[1:]Out[71]: Index([b, c], dtype=object)
索引對象是不可變的,因此不能由用戶改變:
In [72]: index[1] = 'd'Exception Traceback (most recent call last)...Exception: <class 'pandas.core.index.Index'> object is immutable
索引對象的不可變性非常重要,這樣它可以在數(shù)據(jù)結(jié)構(gòu)中結(jié)構(gòu)中安全的共享:
In [73]: index = pd.Index(np.arange(3))In [74]: obj2 = Series([1.5, -2.5, 0], index=index)In [75]: obj2.index is indexOut[75]: True
表格 是庫中內(nèi)建的索引類清單。通過一些開發(fā)努力,索引可以被子類化,來實(shí)現(xiàn)特定坐標(biāo)軸索引功能。多數(shù)用戶不必要知道許多索引對象的知識,但是它們?nèi)匀皇莗andas數(shù)據(jù)模型的重要部分。
Index | 最通用的索引對象,使用Python對象的NumPy數(shù)組來表示坐標(biāo)軸標(biāo)簽。 |
---|---|
Int64Index | 對整形值的特化索引。 |
MultiIndex | “分層”索引對象,表示單個(gè)軸的多層次的索引??梢员徽J(rèn)為是類似的元組的數(shù)組。 |
DatetimeIndex | 存儲納秒時(shí)間戳(使用NumPy的datetime64 dtyppe來表示)。 |
PeriodIndex | 對周期數(shù)據(jù)(時(shí)間間隔的)的特化索引。 |
除了類似于陣列,索引也有類似固定大小集合一樣的功能
In [76]: frame3state Nevada Ohioyear2000 NaN 1.52001 2.4 1.72002 2.9 3.6In [77]: 'Ohio' in frame3.columnsOut[77]: TrueIn [78]: 2003 in frame3.indexOut[78]: False
每個(gè)索引都有許多關(guān)于集合邏輯的方法和屬性,且能夠解決它所包含的數(shù)據(jù)的常見問題。
append | 鏈接額外的索引對象,產(chǎn)生一個(gè)新的索引 |
---|---|
diff | 計(jì)算索引的差集 |
intersection | 計(jì)算交集 |
union | 計(jì)算并集 |
isin | 計(jì)算出一個(gè)布爾數(shù)組表示每一個(gè)值是否包含在所傳遞的集合里 |
delete | 計(jì)算刪除位置i的元素的索引 |
drop | 計(jì)算刪除所傳遞的值后的索引 |
insert | 計(jì)算在位置i插入元素后的索引 |
is_monotonic | 返回True,如果每一個(gè)元素都比它前面的元素大或相等 |
is_unique | 返回True,如果索引沒有重復(fù)的值 |
unique | 計(jì)算索引的唯一值數(shù)組 |
pandas對象的一個(gè)關(guān)鍵的方法是 reindex ,意味著使數(shù)據(jù)符合一個(gè)新的索引來構(gòu)造一個(gè)新的對象。
reindex更多的不是修改pandas對象的索引,而只是修改索引的順序,如果修改的索引不存在就會(huì)使用默認(rèn)的None代替此行。且不會(huì)修改原數(shù)組,要修改需要使用賦值語句。
index | 作為索引的新序列??梢允撬饕龑?shí)例或任何類似序列的Python數(shù)據(jù)結(jié)構(gòu)。一個(gè)索引被完全使用,沒有任何拷貝。 |
---|---|
method | 插值(填充)方法,見表格5-4的選項(xiàng) |
fill_value | 代替重新索引時(shí)引入的缺失數(shù)據(jù)值 |
limit | 當(dāng)前向或后向填充時(shí),最大的填充間隙 |
level | 在多層索引上匹配簡單索引,否則選擇一個(gè)子集 |
copy | 如果新索引與就的相等則底層數(shù)據(jù)不會(huì)拷貝。默認(rèn)為True(即始終拷貝) |
In [79]: obj = Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c'])In [80]: objd 4.5b 7.2a -5.3c 3.6
在Series上調(diào)用 reindex 重排數(shù)據(jù),使得它符合新的索引,如果那個(gè)索引的值不存在就引入缺失數(shù)據(jù)值:
In [81]: obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'])In [82]: obj2a -5.3b 7.2c 3.6d 4.5e NaNIn [83]: obj.reindex(['a', 'b', 'c', 'd', 'e'], fill_value=0)a -5.3b 7.2c 3.6d 4.5e 0.0
為了對時(shí)間序列這樣的數(shù)據(jù)排序,當(dāng)重建索引的時(shí)候可能想要對值進(jìn)行內(nèi)插或填充。 method 選項(xiàng)可以是你做到這一點(diǎn),使用一個(gè)如ffill 的方法來向前填充值:
In [84]: obj3 = Series(['blue', 'purple', 'yellow'], index=[0, 2, 4])In [85]: obj3.reindex(range(6), method='ffill')0 blue1 blue2 purple3 purple4 yellow5 yellow
method 選項(xiàng)的清單
參數(shù) | 描述 |
---|---|
ffill或pad | 前向(或進(jìn)位)填充 |
bfill或backfill | 后向(或進(jìn)位)填充 |
對于DataFrame, reindex 可以改變(行)索引,列或兩者。當(dāng)只傳入一個(gè)序列時(shí),結(jié)果中的行被重新索引了:
In [86]: frame = DataFrame(np.arange(9).reshape((3, 3)), index=['a', 'c', 'd'], columns=['Ohio', 'Texas', 'California'])In [87]: frame Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8
使用 columns 關(guān)鍵字可以是列重新索引:
In [90]: states = ['Texas', 'Utah', 'California']In [91]: frame.reindex(columns=states) Texas Utah Californiaa 1 NaN 2c 4 NaN 5d 7 NaN 8
DataFrame重命名列columns方法2:
df.rename(columns={'age': 'x', 'fat_percent': 'y'})
一次可以對兩個(gè)重新索引,可是插值只在行側(cè)(0坐標(biāo)軸)進(jìn)行:
In [92]: frame.reindex(index=['a', 'b', 'c', 'd'], method='ffill', columns=states) Texas Utah Californiaa 1 NaN 2b 1 NaN 2c 4 NaN 5d 7 NaN 8
正如你將看到的,使用帶標(biāo)簽索引的 ix 可以把重新索引做的更簡單:
In [93]: frame.ix[['a', 'b', 'c', 'd'], states] Texas Utah Californiaa 1 NaN 2b NaN NaN NaNc 4 NaN 5d 7 NaN 8
df.loc[df[len(df.columns) - 1] > 0.0, len(df.columns) - 1] = 1.0不建議設(shè)置不提示:pd.options.mode.chained_assignment = None # default='warn'
通過.ix選擇的數(shù)據(jù)是一個(gè)copy的數(shù)據(jù),修改這個(gè)選擇不會(huì)修改原數(shù)據(jù),而.loc是修改原數(shù)據(jù)。
The .ix object tries to do more than one thing, and for anyone who has read anything about clean code, this is a strong smell.
Given this dataframe:
df = pd.DataFrame({"a": [1,2,3,4], "b": [1,1,2,2]})
Two behaviors:
dfcopy = df.ix[:,["a"]]dfcopy.a.ix[0] = 2
Behavior one: dfcopy is now a stand alone dataframe. Changing it will not change df
df.ix[0, "a"] = 3
Behavior two: This changes the original dataframe.
Use .loc instead
The pandas developers recognized that the .ix object was quite smelly[speculatively] and thus created two new objects which helps in the accession and assignment of data.
.loc is faster, because it does not try to create a copy of the data.
.loc is meant to modify your existing dataframe inplace, which is more memory efficient.
.loc is predictable, it has one behavior.
[Returning a view versus a copy]
>>>obj = Series(range(5), index=['a','a','b','b','c'])
>>>obj
a 0
a 1
b 2
b 3
c 4
驗(yàn)證是否是唯一的
>>>obj.index.is_unique
False
[MultiIndex / Advanced Indexing]
from: http://blog.csdn.net/pipisorry/article/details/18012125
ref: [Indexing and Selecting Data?]*