pandas(二) -- Dataframe创建及索引
生活随笔
收集整理的這篇文章主要介紹了
pandas(二) -- Dataframe创建及索引
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Dataframe創(chuàng)建
- 輸出
- 添加索引
2. 由Series組成的字典
較短的序列補0
one two a 0.065605 0.217466 b 0.973106 0.908904 c NaN 0.663079Dataframe索引與切片
列索引和行索引
df
1. 列索引
按照列名選擇列,只選擇一列輸出Series,選擇多列輸出Dataframe
2. 行索引
按照index選擇行,只選擇一行輸出Series,選擇多行輸出Dataframe
df.loc['one'] – 按標(biāo)簽索引
df.iloc[0] – 按位置索引
data3
a 94.473099 b 30.077407 c 70.953102 d 9.416436 Name: one, dtype: float64 <class 'pandas.core.series.Series'>data4
a b c d one 94.473099 30.077407 70.953102 9.416436 two 41.958628 15.709462 47.400670 56.909647 <class 'pandas.core.frame.DataFrame'>data5
a b c d one 94.473099 30.077407 70.953102 9.416436 two 41.958628 15.709462 47.400670 56.909647-
df.iloc[] - 按照整數(shù)位置做行索引
- 單位置索引 df.iloc[0] ———與 df.loc['one']相同
- 多位置索引 df.iloc[[2,1]] ———與 df.loc['three','two']相同
- 切片索引 df.iloc[0:2]———與 df.loc['one':'three']相同
3. 布爾型索引
df
- 布爾型矩陣索引
b1 = df < 20得到與df同型的矩陣
通過布爾型矩陣索引df[b1],False處的值為NaN,True的為相應(yīng)值
a b c d one NaN NaN NaN NaN two NaN 12.887189 NaN NaN three NaN NaN 12.686749 NaN four NaN NaN NaN 18.956917- 布爾型序列/行索引
b2 = df['a'] > 50,得到布爾型序列
布爾型序列索引,得到的是布爾型序列為true所在的行
a b c d one 52.462365 92.336489 95.512607 85.587735 three 90.755125 98.826032 12.686749 99.404063 four 75.758254 97.520349 36.782117 18.956917不能通過相似的方法對行進(jìn)行判斷。列得到的是列名,與原始的DataFrame的index['one','two','three','four'],無法匹配
錯誤提示Boolean Series key will be reindexed to match DataFrame index.
通過行索引方式為。df在行索引為真時,為原始值,其余地方為NaN
多列索引和多行索引
- 多重索引:比如同時索引行和列
df['a'].loc[['one','three']]
總結(jié)
以上是生活随笔為你收集整理的pandas(二) -- Dataframe创建及索引的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pandas(一)-- Series创建
- 下一篇: pandas(三) -- DataFra