国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

對pandas的算術運算和數據對齊實例詳解

2020-01-04 13:44:43
字體:
來源:轉載
供稿:網友

pandas可以對不同索引的對象進行算術運算,如果存在不同的索引對,結果的索引就是該索引對的并集。

一、算術運算

a、series的加法運算

  s1 = Series([1,2,3],index=["a","b","c"])  s2 = Series([4,5,6],index=["a","c","e"])  print(s1+s2)  '''  a  5.0  b  NaN  c  8.0  e  NaN  '''

sereis相加會自動進行數據對齊操作,在不重疊的索引處會使用NA(NaN)值進行填充,series進行算術運算的時候,不需要保證series的大小一致。

b、DataFrame的加法運算

  d1 = np.arange(1,10).reshape(3,3)  dataFrame1 = DataFrame(d1,index=["a","b","c"],columns=["one","two","three"])  d2 = np.arange(1,10).reshape(3,3)  dataFrame2 = DataFrame(d2,index=["a","b","e"],columns=["one","two","four"])  print(dataFrame1+dataFrame2)  '''    four one three  two  a  NaN 2.0  NaN  4.0  b  NaN 8.0  NaN 10.0  c  NaN NaN  NaN  NaN  e  NaN NaN  NaN  NaN  '''

dataFrame相加時,對齊操作需要行和列的索引都重疊的時候才回相加,否則會使用NA值進行填充。

二、指定填充值

  s1 = Series([1,2,3],index=["a","b","c"])  s2 = Series([4,5,6],index=["a","c","e"])  print( s1.add(s2,fill_value=0))  '''  a  5.0  b  2.0  c  8.0  e  6.0  '''

需要注意的時候,使用add方法對兩個series進行相加的時候,設置fill_value的值是對于不存在索引的series用指定值進行填充后再進行相加。除了加法add,還有sub減法,div除法,mul乘法,使用方式與add相同。DataFrame與series一樣。

  s1 = Series([1,2,3],index=["a","b","c"])  s2 = Series([4,5,6],index=["a","c","e"])  print(s2.reindex(["a","b","c","d"],fill_value=0))  '''  a  4  b  0  c  5  d  0  '''  s3 = s1 + s2  print(s3.reindex(["a","b","c","e"],fill_value=0))  '''  a  5.0  b  NaN  c  8.0  e  NaN  '''

使用reindex進行填充的時候,需要注意的是,不能對已經是值為NaN的進行重新賦值,只能對使用reindex之前不存在的所以使用指定的填充值,DataFrame也是一樣的。

三、DataFrame與Series的混合運算

a、DataFrame的行進行廣播

  a = np.arange(9).reshape(3,3)  d = DataFrame(a,index=["a","b","c"],columns=["one","two","three"])  #取d的第一行為Series  s = d.ix[0]  print(d+s)  '''    one two three  a  0  2   4  b  3  5   7  c  6  8   10  '''

b、DataFrame的列進行廣播

  a = np.arange(9).reshape(3,3)  d = DataFrame(a,index=["a","b","c"],columns=["one","two","three"])  #取d的第一列為Series  s = d["one"]  print(d.add(s,axis=0))  '''    one two three  a  0  1   2  b  6  7   8  c  12  13   14  '''

對列進行廣播的時候,必須要使用add方法,而且還要將axis設置為0,不然就會得到下面的結果

  print(d.add(s))  '''    a  b  c one three two  a NaN NaN NaN NaN  NaN NaN  b NaN NaN NaN NaN  NaN NaN  c NaN NaN NaN NaN  NaN NaN  '''

以上這篇對pandas的算術運算和數據對齊實例詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 广宁县| 襄汾县| 文成县| 黄龙县| 礼泉县| 临沭县| 贺兰县| 焉耆| 辽宁省| 古交市| 乾安县| 肇源县| 台湾省| 肇东市| 化隆| 永福县| 壶关县| 满洲里市| 育儿| 余干县| 长子县| 柳江县| 鲜城| 东台市| 商水县| 汶川县| 霍城县| 甘南县| 漳浦县| 利辛县| 武宁县| 鹰潭市| 杭州市| 五台县| 封丘县| 辽宁省| 大余县| 蓬溪县| 高清| 邮箱| 建宁县|