我已經使用 pandas 閱讀了 CVS 檔案,并設法使用.iloc.
Prem_results = pd.read_csv("../data sets analysis/prem/result.csv")
Prem_results.iloc[:320:20,:]
Prem_results.iloc[1:320:20,:]
Prem_results.iloc[2:320:20,:]
Prem_results.iloc[3:320:20,:]
有沒有一種方法可以iloc將每 20 行的第一 4 行列印在一起,而不是像我現在這樣單獨列印?抱歉,如果這對 python 和使用 pandas 來說都是相當新的措辭。
uj5u.com熱心網友回復:
使用groupby.head:
Prem_results.groupby(np.arange(len(Prem_results)) // 20).head(4)
uj5u.com熱心網友回復:
您可以像這樣將切片連接在一起:
pd.concat([df[i::20] for i in range(4)]).sort_index()
MCVE:
df = pd.DataFrame({'col1':np.arange(1000)})
pd.concat([df[i::20] for i in range(4)]).sort_index().head(20)
輸出:
col1
0 0
1 1
2 2
3 3
20 20
21 21
22 22
23 23
40 40
41 41
42 42
43 43
60 60
61 61
62 62
63 63
80 80
81 81
82 82
83 83
從 0 開始,每 20 行一次
從 1 開始,每 20 行一次
從 2 開始,每 20 行一次
并且,從 3 開始,每 20 行一次。
uj5u.com熱心網友回復:
您也可以在閱讀 csv 本身時執行此操作。
df = pd.DataFrame()
for chunk in pd.read_csv(file_name, chunksize = 20):
df = pd.concat((df, chunk.head(4)))
更多資源:您可以在此處閱讀更多關于chunksizePandas 官方檔案中的用法的資訊。
我在這里也有一篇關于它的用法的帖子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/445121.html
