Python:pandas之DataFrame常用操作


定義一個df:

dates = pd.date_range('20180101', periods=6)
df = pd.DataFrame(np.arange(24).reshape(6, 4), index=dates, columns=['A', 'B', 'C', 'D'])
print(df)  #類型為pandas.core.frame.DataFrame
''' A B C D 2018-01-01 0 1 2 3 2018-01-02 4 5 6 7 2018-01-03 8 9 10 11 2018-01-04 12 13 14 15 2018-01-05 16 17 18 19 2018-01-06 20 21 22 23 '''

一個DataFrame相當於一張數據表,我們用常用sql操作來類比說明pandas的DataFrame操作。

DataFrame和sql操作不同的是:
對df選擇的元素進行賦值操作會將df返回的集合的每個元素都賦值成功,而sql只會返回一個集合。

選擇列:

df.A      # select A from df; 返回值類型為一個序列pandas.core.series.Series
df['A']   # 同上
df[['A','C']] # select A, C from df; 類型為DataFrame

條件篩選:

df.loc[df.A > 0, 'B']     # select B from df where A>0;
df.loc[(df.A>0)&(df.D<20), ['B', 'C']]  # select B,C from df where A>0 and D<20;
df[['B', 'C']].loc[(df.A>0)&(df.D<20)]  # 同上


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM