pandas21 讀csv檔案read_csv(7.索引)(詳細 tcy)
阿新 • • 發佈:2018-12-29
索引 2018/12/26
目錄: 第1部分:csv文字檔案讀寫 pandas 讀csv檔案read_csv(1.文字讀寫概要)https://mp.csdn.net/postedit/85289371 pandas 讀csv檔案read_csv(2.read_csv引數介紹)https://mp.csdn.net/postedit/85289928 pandas 讀csv檔案read_csv(3.dtypes指定列資料型別)https://mp.csdn.net/postedit/85290575 pandas 讀csv檔案read_csv(4.to_csv文字資料寫)https://mp.csdn.net/postedit/85290962 pandas 讀csv檔案read_csv(5.文字資料讀寫例項)https://mp.csdn.net/postedit/85291123 pandas 讀csv檔案read_csv(6.命名和使用列)https://mp.csdn.net/postedit/85291430 pandas 讀csv檔案read_csv(7.索引)https://mp.csdn.net/postedit/85291658 pandas 讀csv檔案read_csv(8.方言和分隔符)https://mp.csdn.net/postedit/85291994 pandas 讀csv檔案read_csv(9.浮點轉換和NA值)https://mp.csdn.net/postedit/85292391 pandas 讀csv檔案read_csv(10.註釋和空行)https://mp.csdn.net/postedit/85292609 pandas 讀csv檔案read_csv(11.日期時間處理) https://mp.csdn.net/postedit/85292925 pandas 讀csv檔案read_csv(12.迭代和塊)https://mp.csdn.net/postedit/85293639 pandas 讀csv檔案read_csv(13.read_fwf讀固定寬度資料)https://mp.csdn.net/postedit/85294010 第2部分: pandas hdf檔案讀寫簡要https://mp.csdn.net/postedit/85294299 pandas excel讀寫簡要https://mp.csdn.net/postedit/85294545 第3部分: python中csv模組用法tcy https://mp.csdn.net/postedit/85228189 pandas讀csv檔案read_csv錯誤解決辦法7種https://mp.csdn.net/postedit/85228808 pandas to_string用法https://mp.csdn.net/postedit/85294935
# 例項1:帶有“隱式”索引列的檔案 data='A,B,C\n' \ '20190101,a,1,2\n' \ '20190102,b,3,4\n' \ '20190103,c,4,5' # 標題條目少於資料列數的檔案 pd.read_csv(StringIO(data))# 假設第一列用作以下索引 A B C 20190101 a 1 2 20190102 b 3 4 20190103 c 4 5 # 日期未自動解析 df = pd.read_csv(StringIO(data), parse_dates=True) df.index # DatetimeIndex(..., dtype='datetime64[ns]', freq=None)
例項2:讀取多行索引
data='year,order,x,y\n' \ '2017,"A",1.2,.6\n' \ '2017,"B",1.5,.5\n' \ '2018,"A",.2,.06\n' \ '2018,"B",.7,.2\n' \ '2018,"C",.8,.3\n' \ '2019,"C",.2,.15\n' \ '2019,"D",.14,.05\n' \ '2019,"E",.5,.15' # 有兩列索引的資料 df = pd.read_csv(StringIO(data), index_col=[0,1]) df = pd.read_csv(StringIO(data), index_col=['year','order']) #等價
x y
year order
2017 A 1.20 0.60
B 1.50 0.50
2018 A 0.20 0.06
B 0.70 0.20
C 0.80 0.30
2019 C 0.20 0.15
D 0.14 0.05
E 0.50 0.15
df.loc[2018]
x y
order
A 0.2 0.06
B 0.7 0.20
C 0.8 0.30
例項3:讀取多列索引
data=',a,a,a,b,c,c\n' \
',ss1,ss2,ss3,ss4,ss5,ss6\n' \
'one,1,2,3,4,5,6\n' \
'two,7,8,9,10,11,12'
pd.read_csv(StringIO(data), header=[0, 1], index_col=0)
a b c
ss1 ss2 ss3 ss4 ss5 ss6
one 1 2 3 4 5 6
two 7 8 9 10 11 12