Python Pandas –操作

Pandas support very useful operations which are illustrated below,

熊貓支持非常有用的操作,如下所示,

Consider the below dataFrame,

考慮下面的dataFrame,

import numpy as np
import pandas as pd
df = pd.DataFrame({
'col1': [1, 2, 3, 4],
'col2': [444, 555, 666, 444],
'col3': ['abc', 'def', 'ghi', 'xyz']
})
print(df.head())
'''
Output:
col1  col2 col3
0     1   444  abc
1     2   555  def
2     3   666  ghi
3     4   444  xyz
'''

在數據框中查找唯一值 (Finding unique values in a data frame)

In order to find unique values from columns,

為了從列中找到唯一值,

# returns numpy array of all unique  values
print(df['col2'].unique() )
# Output: array([444, 555, 666])
# returns length / number of unique values 
# in a numpy array
print(df['col2'].nunique())
# Output: 3
# if we want the table of the unique values
# and how many times they show up
print(df['col2'].value_counts() )
'''
Output:
444    2
555    1
666    1
Name: col2, dtype: int64
'''

從數據框中選擇數據 (Selecting data from a data frame)

Consider the dataFrame,

考慮一下dataFrame,

Using the conditional selection, we could select data as follows,

使用條件選擇,我們可以選擇以下數據,

print(df['col1']>2)
'''
Output:
0    False
1    False
2     True
3     True
Name: col1, dtype: bool
'''
print(df[(df['col1']>2)])
'''
Output:
col1  col2 col3
2     3   666  ghi
3     4   444  xyz
'''
print(df[df['col1']>2 & (df['col2']==44)])
'''
Output:
col1  col2 col3
0     1   444  abc
1     2   555  def
2     3   666  ghi
3     4   444  xyz
'''

應用方法 (Applied Methods)

Consider a simple method,

考慮一個簡單的方法,

def times2(x):
return x*2

We already are aware that we can grab a column and call a built-in function off of it. Such as below,

我們已經知道我們可以抓住一列并從中調用一個內置函數。 如下

print(df['col1'].sum())
# Output: 10

Now, in order to apply the custom function, such as one defined above (times2), pandas provide an option to do that as well, as explained below,

現在,為了應用自定義功能(例如上面定義的時間(times2)),熊貓也提供了執行此功能的選項,如下所述,

print(df['col2'].apply(times2))
'''
Output:
0     888
1    1110
2    1332
3     888
Name: col2, dtype: int64
'''

Apply built-in functions,

應用內置功能,

print(df['col3'].apply(len))
'''
Output:
0    3
1    3
2    3
3    3
Name: col3, dtype: int64
'''

Apply method will be more powerful, when combined with lambda expressions. For instance,

與lambda表達式結合使用時,apply方法將更強大。 例如,

print(df['col2'].apply(lambda x: x*2))
'''
Output:
0     888
1    1110
2    1332
3     888
Name: col2, dtype: int64
'''

更多操作 (Some more operations)

# returns the columns names
print(df.columns) 
# Output: Index(['col1', 'col2', 'col3'], dtype='object')
#since this is a rangeindex, it actually reports 
# start, stop and step values too
print(df.index)
# Output: RangeIndex(start=0, stop=4, step=1)
# sort by column
print(df.sort_values('col2'))
'''
Output:
col1  col2 col3
0     1   444  abc
3     4   444  xyz
1     2   555  def
2     3   666  ghi
'''

In the above result, note that the index values doesn't change, this is to ensure that the values is retained.

在上面的結果中,請注意索引值不會更改,這是為了確保保留這些值。

isnull

一片空白

# isnull
print(df.isnull())
'''
Output
col1   col2   col3
0  False  False  False
1  False  False  False
2  False  False  False
3  False  False  False
'''

The isnull() will return a dataframe of booleans indicating whether or not the value was null or not. In the above, we get a boolean of all false because we have nulls in our dataframe.

notull()將返回一個布爾值數據框,指示該值是否為null。 在上面的代碼中,由于我們的數據幀中包含null,因此我們得到的布爾值均為false。

Drop NAN values

降低NAN值

print(df.dropna())
'''
Output:
col1  col2 col3
0     1   444  abc
1     2   555  def
2     3   666  ghi
3     4   444  xyz
'''

Fill NAN values with custom values

用自定義值填充NAN值

df = pd.DataFrame({
'col1': [1, 2, 3, np.nan],
'col2': [np.nan, 555, 666, 444],
'col3': ['abc', 'def', 'ghi', 'xyz']
})
print(df)
'''
Output:
col1   col2 col3
0   1.0    NaN  abc
1   2.0  555.0  def
2   3.0  666.0  ghi
3   NaN  444.0  xyz
'''
print(df.fillna('FILL'))
'''
Output:
col1  col2 col3
0     1  FILL  abc
1     2   555  def
2     3   666  ghi
3  FILL   444  xyz
'''

Usage of pivot table

數據透視表的用法

This methodology will be familiar for the Advanced Excel users. Consider a new dataFrame,

Advanced Excel用戶將熟悉這種方法。 考慮一個新的dataFrame,

data = {
'A': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'],
'B': ['one', 'one', 'two', 'two', 'one', 'one'],
'C': ['x', 'y', 'x', 'y', 'x', 'y'],
'D': [1, 3, 2, 5, 4, 1]
}
df = pd.DataFrame(data)
print(df)
'''
Output:
A    B  C  D
0  foo  one  x  1
1  foo  one  y  3
2  foo  two  x  2
3  bar  two  y  5
4  bar  one  x  4
5  bar  one  y  1
'''

The pivot table, creates a multi index dataFrame. The pivot table takes three main arguments, the values, the index and the columns.

數據透視表創建一個多索引dataFrame。 數據透視表采用三個主要參數,即值,索引和列。

print(df.pivot_table(values='D',index=['A', 'B'],columns=['C']))
'''
Output:
C        x    y
A    B            
bar one  4.0  1.0
two  NaN  5.0
foo one  1.0  3.0
two  2.0  NaN
'''

翻譯自: https://www.includehelp.com/python/python-pandas-operations.aspx

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/540760.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540760.shtml
英文地址,請注明出處:http://en.pswp.cn/news/540760.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

有道詞典總顯示無法連接服務器,有道詞典無法聯網提示網絡已斷開該怎么辦

人們使用電腦時候最不想看到的事情之一就是上不了網了,無論是工作還是玩游戲時候都很不爽。電腦能正常上網,但是有道詞典始終無法聯網。這是怎么回事呢?下面一起看看!方法步驟1、我是win8的系統。有道詞典無法聯網后,我在網上查了一下方法&a…

ajax+lazyload時lazyload失效問題及解決

最近寫公司的項目的時候遇到一個關于圖片加載的問題,所做的頁面是一個商城的商品列表頁,其中需要顯示商品圖片,名稱等信息,因為商品列表可能會很長,所以其中圖片需要滑到可以顯示的區域再進行加載。 首先我的圖片加載插…

手游pubg mobile服務器正在維護,PUBG Mobile Download Failed怎么解決

《PUBG Mobile》國際服出現下載失敗的情況,你將會收到“Download Failed”提示,你就需要按照下述的方法去解決該問題。注意:如果下載不了 請復制瀏覽器上的鏈接 https:/http://pic.81857.netownloads.gradle.orghttp://pic.81857.netistribut…

Python自動化運維之常用模塊—logging

在現實生活中,記錄日志非常重要。銀行轉賬時會有轉賬記錄;如果有出現什么問題,人們可以通過日志數據來搞清楚到底發生了什么。 對于系統開發、調試以及運行,記錄日志都是同樣的重要。如果沒有日志記錄,程序崩潰時你…

Sys.WORD_SIZE Julia中的常量

Julia| Sys.WORD_SIZE常數 (Julia | Sys.WORD_SIZE Constant) Sys.WORD_SIZE is a constant of the Int64 type in Julia programming language, it is used to get the standard word size of the current system. Sys.WORD_SIZE是Julia編程語言中Int64類型的常量,…

ftp服務器如何配置多個文件夾,ftp服務器如何配置多個文件夾

ftp服務器如何配置多個文件夾 內容精選換一換Model File:模型文件。單擊右側的文件夾圖標,在后臺服務器sample所在路徑(工程目錄/run/out/test_data/model)選擇需要轉化的模型對應的*.prototxt文件,并上傳。Weight File:權重文件。請自行從https://obs-m…

scala 方法調用_Scala中的方法調用

scala 方法調用Scala方法調用 (Scala Method Invocation) Method invocation is the legal and correct technique to call a method in Scala programming language. The methods of a class are usually accessed by using two methods. 方法調用是用Scala編程語言調用方法的…

docker lnmp php

使用 Docker 構建 LNMP 環境https://segmentfault.com/a/1190000008833012Docker 快速上手指南https://segmentfault.com/a/1190000008822648#articleHeader44

根據分類id找出父類id

2019獨角獸企業重金招聘Python工程師標準>>> 數組格式要求 id > pid $columns [ 1 > 0, 10 > 1, 200 > 10 ]; public function getP($columns,$pid) { 模擬 $pid 200; $arr $columns; while($arr[$pid]) { …

不穩定學習器適合做基分類器_分類穩定性

不穩定學習器適合做基分類器什么是分類? (What is sorting?) It means to arrange data elements in increasing or decreasing order. There are many algorithms to do so like mergesort, quicksort, counting sort etc but there are pros and cons of each al…

JavaScript基礎學習--05自定義屬性、索引值

Demos&#xff1a; https://github.com/jiangheyan/JavaScriptBase 一、自定義屬性1、讀寫操作<input abc"123" type"button" value"按鈕" />//讀寫&#xff1a; var aBtn document.getElementsByTagName(input); aBtn[0].abc 456; 2、…

有線電視pcr是什么意思_有線電視的完整形式是什么?

有線電視pcr是什么意思有線電視&#xff1a;社區訪問電視 (CATV: Community Access Television) CATV is an abbreviation of "Community Access Television". CATV是“社區訪問電視”的縮寫 。 It is also known as Public Access Television, which is a type of …

桶分類 算法_桶分類算法

桶分類 算法桶分類 (Bucket Sort) Bucket sort is a sorting technique in which array is partitioned into the buckets. By this, each bucket will be sorted individually, by using some another sorting algorithm such as insertion sort. This sorting technique assu…

百度之星初賽(A)——T5

今夕何夕 Problem Description今天是2017年8月6日&#xff0c;農歷閏六月十五。 小度獨自憑欄&#xff0c;望著一輪圓月&#xff0c;發出了“今夕何夕&#xff0c;見此良人”的寂寞感慨。 為了排遣郁結&#xff0c;它決定思考一個數學問題&#xff1a;接下來最近的哪一年里的同…

mycat 不得不說的緣分

1&#xff0c;愕然回首。它在燈火闌珊處關于mysql集群中間件。曾經寫在應用程序里面&#xff0c;由開發者實現&#xff0c;在配置文件中面寫多個數據源&#xff0c;寫庫一個數據源&#xff0c;讀庫一個數據源&#xff0c;笨拙不高效&#xff0c;由于程序猿的差異化。效果并非特…

python創建空元組_用Python創建空元組

python創建空元組Python | 空元組 (Python | empty tuple) In python, we can also create a tuple without having any element. An empty tuple is created using a pair of round brackets, (). 在python中&#xff0c;我們也可以創建一個沒有任何元素的元組 。 使用一對圓括…

共享馬扎的火爆,原來是一場營銷!

如今&#xff0c;人們的生活仿佛已經被“共享化”&#xff1a;上班有共享單車、睡覺有共享床鋪、商場有共享充電寶、去機場有共享巴士……好像除了男女朋友是自己的&#xff0c;其他都要共享了&#xff01;哎&#xff0c;不對&#xff01;前些日子&#xff0c;竟然還真有了共享…

什么是CDP(連續數據保護)?

CDP&#xff1a;連續數據保護 (CDP: Continuous Data Protection) CDP is an abbreviation of "Continuous Data Protection". It is also called as a real-time backup, is a system of data storage that backs up data in an organization or enterprise on a sy…

Git實戰(二)原理

上次的博文Git實戰&#xff08;一&#xff09;版本號控制概述中我們簡介了一下版本號控制系統的概念&#xff0c;重點對版本號控制的三種類型進行了分析和對照&#xff0c;從本篇博文開始我們進入Git的世界&#xff0c;首先介紹一下Git實現版本號控制的原理。 Git與SVN等其它版…

什么是html的混雜模式_HTML的完整形式是什么?

什么是html的混雜模式HTML&#xff1a;超文本標記語言 (HTML: Hyper Text Markup Language) HTML is an abbreviation of Hypertext markup language. Hypertext markup language is a text based standard markup language used to create web pages and design documents whi…