Pandas系列3-DataFrame之增加與刪除

在使用Pandas的過程增刪改查是頻繁使用的操作见转,這一節(jié)主要就是展示DataFrame常用的增加和刪除操作

增加行和增加列

# 增加一列管削,我們可以有兩種方式,如下:
In [345]: df
Out[345]:
   one  two
a    0    1
b    4    5
c    8    9
d   12   13

In [346]: df['three'] = [3, 5, 5, 7]

In [347]: df
Out[347]:
   one  two  three
a    0    1      3
b    4    5      5
c    8    9      5
d   12   13      7

# 或者使用loc
In [369]: df
Out[369]:
   one  two  three
a    0    1      2
b    4    5      6
c    8    9     10
d   12   13     14

In [370]: df.loc[:, "four"] = [1, 4, 5, 9]

In [371]: df
Out[371]:
   one  two  three  four
a    0    1      2     1
b    4    5      6     4
c    8    9     10     5
d   12   13     14     9

需要注意的是使用如上兩種方式增加一列的時候罗心,其數(shù)組的長度必須與原有DataFrame的行數(shù)相同里伯,否則會報如下錯誤

ValueError: Length of values does not match length of index

增加行同樣我們也可以使用loc, 如下:

In [376]: df
Out[376]:
   one  two  three  four
a    0    1      2     3
b    4    5      6     7
c    8    9     10    11
d   12   13     14    15

In [377]: df.loc['e'] = [3, 7, 8, 9]

In [378]: df
Out[378]:
   one  two  three  four
a    0    1      2     3
b    4    5      6     7
c    8    9     10    11
d   12   13     14    15
e    3    7      8     9

但很多時候,我們并不需要row index, 只想自動增加一行渤闷,那么可以通過如下的方式

In [379]: df.loc[df.shape[0]+1] = [3, 5, 9, 9]

In [380]: df
Out[380]:
   one  two  three  four
a    0    1      2     3
b    4    5      6     7
c    8    9     10    11
d   12   13     14    15
e    3    7      8     9
6    3    5      9     9

另外疾瓮,我們還可以將數(shù)據(jù)轉(zhuǎn)化為Series,然后利用concat或者append的方式將其與原有的DataFrame進(jìn)行合并飒箭。這種方式不僅可以添加一行數(shù)據(jù)狼电,也可以一次性添加多行數(shù)據(jù)。

In [392]: df = pd.DataFrame(np.arange(16).reshape((4,4)), index=[1, 2, 3, 4], columns=['a',
     ...:  'b', 'c','d'])

In [393]: df2 = pd.DataFrame(np.arange(16).reshape((4,4)), index=[5, 6, 7, 8], columns=['a'
     ...: , 'b', 'c','d'])

# 這里相當(dāng)于添加了多行數(shù)據(jù)
In [394]: pd.concat([df, df2])
Out[394]:
    a   b   c   d
1   0   1   2   3
2   4   5   6   7
3   8   9  10  11
4  12  13  14  15
5   0   1   2   3
6   4   5   6   7
7   8   9  10  11
8  12  13  14  15

更多關(guān)于concat和append將在后續(xù)的章節(jié)詳細(xì)講解弦蹂。

刪除行和刪除列

In [751]: df
Out[751]:
           age  color    food  height  score state
Jane        30   blue   Steak     178    4.6    NY
Nick         2  green    Lamb     181    8.3    TX
Aaron       12    red   Mango     178    9.0    FL
Penelope     4  white   Apple     178    3.3    AL
Dean        32   gray  Cheese     175    1.8    AK
Christina   33  black   Melon     178    9.5    TX
Cornelia    69    red   Beans     178    2.2    TX

# 使用drop刪除index為'Dean'的行
In [752]: df.drop(['Dean'])
Out[752]:
           age  color   food  height  score state
Jane        30   blue  Steak     178    4.6    NY
Nick         2  green   Lamb     181    8.3    TX
Aaron       12    red  Mango     178    9.0    FL
Penelope     4  white  Apple     178    3.3    AL
Christina   33  black  Melon     178    9.5    TX
Cornelia    69    red  Beans     178    2.2    TX

In [749]: df
Out[749]:
           age  color    food  height  score state
Jane        30   blue   Steak     178    4.6    NY
Nick         2  green    Lamb     181    8.3    TX
Aaron       12    red   Mango     178    9.0    FL
Penelope     4  white   Apple     178    3.3    AL
Dean        32   gray  Cheese     175    1.8    AK
Christina   33  black   Melon     178    9.5    TX
Cornelia    69    red   Beans     178    2.2    TX

# 使用drop刪除名為'height'的列肩碟,注意需要使用axis=1
# 使用inplace來空值是在同一塊內(nèi)存還是copy
In [750]: df.drop(['height'], axis=1, inplace=True)
Out[750]:
           age  color    food  score state
Jane        30   blue   Steak    4.6    NY
Nick         2  green    Lamb    8.3    TX
Aaron       12    red   Mango    9.0    FL
Penelope     4  white   Apple    3.3    AL
Dean        32   gray  Cheese    1.8    AK
Christina   33  black   Melon    9.5    TX
Cornelia    69    red   Beans    2.2    TX

# drop多列
df.drop(['height', 'food'], axis=1, inplace=True)

條件刪除

由于在數(shù)據(jù)清洗的過程中經(jīng)常需要刪除不符合條件的record,所以以下這種條件過濾行就非常有用凸椿。需要注意的是削祈,這里是重新生成了一個DataFrame,而不是直接在原有的DataFrame上修改

In [755]: df2 = df[df.color!='blue']

In [756]: df2
Out[756]:
           age  color    food  height  score state
Nick         2  green    Lamb     181    8.3    TX
Aaron       12    red   Mango     178    9.0    FL
Penelope     4  white   Apple     178    3.3    AL
Dean        32   gray  Cheese     175    1.8    AK
Christina   33  black   Melon     178    9.5    TX
Cornelia    69    red   Beans     178    2.2    TX

去重

使用drop_duplicates,我們可以去掉重復(fù)項髓抑,這是一個非常有用的函數(shù)咙崎,下面我們來詳細(xì)分析下

  • 通過參數(shù)subset,指定去重比較時用哪些column。如果不指定則所有的數(shù)據(jù)都會比較吨拍,只有所有列的數(shù)據(jù)都一致的時候才會去掉叙凡,否則不會去掉,如下:
In [459]: df_con2
Out[459]:
  uid  num1  num2
0  a1     1   4.0
1  a2     3   5.0
2  b1     5   7.0
0  a1     2   4.0
1  a2     5   NaN
2  a3     2   2.0

In [460]: df_drop = df_con2.drop_duplicates()

In [461]: df_drop
Out[461]:
  uid  num1  num2
0  a1     1   4.0
1  a2     3   5.0
2  b1     5   7.0
0  a1     2   4.0
1  a2     5   NaN
2  a3     2   2.0

我們可以讓兩個dataframe只比較uid列密末,只要這一列的數(shù)據(jù)重復(fù)握爷,我們就認(rèn)為重復(fù),如下:

In [462]: df_drop2 = df_con2.drop_duplicates(subset='uid')

In [463]: df_drop2
Out[463]:
  uid  num1  num2
0  a1     1   4.0
1  a2     3   5.0
2  b1     5   7.0
2  a3     2   2.0
  • 另外從上邊的例子可以看出严里,其去重是去掉了后邊出現(xiàn)的重復(fù)的項新啼,我們也可以保留后邊的項,將前邊的項去掉刹碾,那么就需要使用keep參數(shù)燥撞。另外,我們也可以直接在DataFrame中進(jìn)行去重迷帜,而不需要再另外copy一份數(shù)據(jù)物舒,這可以通過inplace=True來實現(xiàn),示例如下:
In [453]: df_con
Out[453]:
  uid  num1  num2
0  a1     1   4.0
1  a2     3   5.0
2  b1     5   7.0
0  a1     2   4.0
1  a2     5   NaN
2  a3     2   2.0

# 注意這里沒有賦值操作戏锹,因為使用了inplace=True
# 使用keep='last'用于保存后邊的數(shù)據(jù)冠胯,刪除前邊的重復(fù)項
In [454]: df_con.drop_duplicates(subset='uid', keep='last', inplace=True)

In [455]: df_con
Out[455]:
  uid  num1  num2
2  b1     5   7.0
0  a1     2   4.0
1  a2     5   NaN
2  a3     2   2.0

References

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市锦针,隨后出現(xiàn)的幾起案子荠察,更是在濱河造成了極大的恐慌,老刑警劉巖奈搜,帶你破解...
    沈念sama閱讀 219,427評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件悉盆,死亡現(xiàn)場離奇詭異,居然都是意外死亡馋吗,警方通過查閱死者的電腦和手機(jī)焕盟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來宏粤,“玉大人脚翘,你說我怎么就攤上這事∩碳埽” “怎么了堰怨?”我有些...
    開封第一講書人閱讀 165,747評論 0 356
  • 文/不壞的土叔 我叫張陵芥玉,是天一觀的道長蛇摸。 經(jīng)常有香客問我,道長灿巧,這世上最難降的妖魔是什么赶袄? 我笑而不...
    開封第一講書人閱讀 58,939評論 1 295
  • 正文 為了忘掉前任揽涮,我火速辦了婚禮,結(jié)果婚禮上饿肺,老公的妹妹穿的比我還像新娘蒋困。我一直安慰自己,他們只是感情好敬辣,可當(dāng)我...
    茶點故事閱讀 67,955評論 6 392
  • 文/花漫 我一把揭開白布雪标。 她就那樣靜靜地躺著,像睡著了一般溉跃。 火紅的嫁衣襯著肌膚如雪村刨。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,737評論 1 305
  • 那天撰茎,我揣著相機(jī)與錄音嵌牺,去河邊找鬼。 笑死龄糊,一個胖子當(dāng)著我的面吹牛逆粹,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播炫惩,決...
    沈念sama閱讀 40,448評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼僻弹,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了他嚷?” 一聲冷哼從身側(cè)響起奢方,我...
    開封第一講書人閱讀 39,352評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎爸舒,沒想到半個月后蟋字,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,834評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡扭勉,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,992評論 3 338
  • 正文 我和宋清朗相戀三年鹊奖,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片涂炎。...
    茶點故事閱讀 40,133評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡忠聚,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出唱捣,到底是詐尸還是另有隱情两蟀,我是刑警寧澤,帶...
    沈念sama閱讀 35,815評論 5 346
  • 正文 年R本政府宣布震缭,位于F島的核電站赂毯,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜党涕,卻給世界環(huán)境...
    茶點故事閱讀 41,477評論 3 331
  • 文/蒙蒙 一烦感、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧膛堤,春花似錦手趣、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至燕耿,卻和暖如春怯晕,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背缸棵。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評論 1 272
  • 我被黑心中介騙來泰國打工舟茶, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人堵第。 一個月前我還...
    沈念sama閱讀 48,398評論 3 373
  • 正文 我出身青樓吧凉,卻偏偏與公主長得像,于是被迫代替她去往敵國和親踏志。 傳聞我的和親對象是個殘疾皇子阀捅,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,077評論 2 355

推薦閱讀更多精彩內(nèi)容