Pandas技巧分享之創(chuàng)建測試數(shù)據(jù)
學習pandas的過程中,為了嘗試pandas提供的各類功能強大的函數(shù),常常需要花費很多時間去創(chuàng)造測試數(shù)據(jù)。
在pandas中,快速創(chuàng)建測試數(shù)據(jù)可以更快的評估 pandas 函數(shù)。
通過生成一組測試數(shù)據(jù),可以評估例如 read_csv、read_excel、groupby等函數(shù),以確保這些函數(shù)在處理不同數(shù)據(jù)格式和結構時都能正常工作。
本篇介紹一些快速創(chuàng)建測試數(shù)據(jù)的方法,提高學習pandas的效率。
1. 一般方法
一般創(chuàng)建測試數(shù)據(jù)的有兩種:
- 一種是直接創(chuàng)建每行每列的數(shù)據(jù)
- 用 numpy 隨機生成二維數(shù)組
1.1. 直接創(chuàng)建數(shù)據(jù)
這種方式之前的視頻中已經(jīng)多次使用,直接創(chuàng)建數(shù)據(jù)雖然麻煩,但好處是每個數(shù)據(jù)都可控,不論是數(shù)據(jù)類型還是值都高度可控。
import pandas as pd
df = pd.DataFrame(
{
"數(shù)學": [100, 88, 94, 76, 84],
"語文": [98, 80, 86, 76, 90],
"英語": [95, 91, 86, 95, 83],
},
index=["小紅", "小明", "小汪", "小李", "小張"],
)
df
1.2. 隨機二維數(shù)組
隨機生成二維數(shù)組需要用到numpy庫,通過 numpy生成隨機二維數(shù)據(jù),然后將其轉換為pandas的DataFrame。
比如,下面生成一個3行4列的隨機數(shù)據(jù):
pd.DataFrame(np.random.rand(3, 4))

上面的數(shù)據(jù)是隨機的,每次運行產生的結果會不一樣。
隨機創(chuàng)建數(shù)據(jù)時,也可以設置索引和列名。
pd.DataFrame(
np.random.rand(3, 4),
index=["row1", "row2", "row3"],
columns=["col1", "col2", "col3", "col4"],
)
2. 特殊技巧
上面介紹隨機生成數(shù)據(jù)的方法只能生成浮點型數(shù)據(jù),而且索引和列名都只能是默認的自增數(shù)字,數(shù)據(jù)的多樣性不夠。
下面介紹pandas自身提供的一些隨機生成數(shù)據(jù)方法,可以生成不同類型的隨機數(shù)據(jù)。
2.1. makeDataFrame
makeDataFrame() 方法會隨機創(chuàng)建一個 30x4 的數(shù)據(jù)集。
df = pd.util.testing.makeDataFrame() print(df.shape) df.head()

索引是隨機字符串。
2.2. makeMissingDataFrame
makeMissingDataFrame() 方法會隨機創(chuàng)建一個 30x4 包含缺失值的數(shù)據(jù)集,缺失值的位置也是隨機的。
df = pd.util.testing.makeMissingDataframe() print(df.shape) df.head()

2.3. makeTimeDataFrame
makeTimeDataFrame() 方法會隨機創(chuàng)建一個 30x4 包含的數(shù)據(jù)集,索引是自增的日期。
df = pd.util.testing.makeTimeDataFrame() print(df.shape) df.head()

2.4. makeMixedDataFrame
makeMixedDataFrame()方法會隨機創(chuàng)建一個 5x4的數(shù)據(jù)集,其中列的類型是多樣的,有字符串,日期和數(shù)值。
df = pd.util.testing.makeMixedDataFrame() print(df.shape) df

3. 補充
上面介紹的方法生成的數(shù)據(jù)集不大,如果需要生成數(shù)據(jù)量較大的數(shù)據(jù)集的話,可以循環(huán)生成DataFrame,然后再拼接在一起。
上面介紹的方法,每次生成的數(shù)據(jù)集的值是隨機的,不用擔心拼接后全是重復的數(shù)據(jù)。
此外,除了上面介紹的方法之外,pd.util.testing 還有其他一些創(chuàng)建數(shù)據(jù)的方法,歡迎大家去探索,使用。
到此這篇關于Pandas技巧分享之創(chuàng)建測試數(shù)據(jù)的文章就介紹到這了,更多相關Pandas創(chuàng)建測試數(shù)據(jù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python利用jmespath模塊進行json數(shù)據(jù)處理
jmespath是python的第三方模塊,是需要額外安裝的。它在python原有的json數(shù)據(jù)處理上做出了很大的貢獻。本文將詳細介紹如何利用jmespath實現(xiàn)json數(shù)據(jù)處理,需要的可以參考一下2022-03-03

