我想列印 2007 年 2 月資料幀的最后 10 行,但不考慮最后一行。
資料框包括日期作為索引,其中包括數值的幾列。
到目前為止,我已經嘗試過這種方法:
df['2007-02'].iloc[:-1,:].last('10D')
是否有另一種列印方式但忽略最后一行?而不是洗掉它。此外,通過使用這種方法,我會收到一個未來警告,我可能會使用其他不會很快被棄用的技??術嗎?
uj5u.com熱心網友回復:
您的 FutureWarning 被引發是因為您不使用locfor df['2007-02']。
您可以獲取最后 11 行并排除最后一行:
>>> df.loc['2007-02'].last('11D')[:-1]
# OR
>>> df.loc['2007-02'][:-1].last('10D')
A B C
2007-02-18 2 1 1
2007-02-19 6 10 7
2007-02-20 4 8 2
2007-02-21 2 3 3
2007-02-22 5 5 1
2007-02-23 7 2 5
2007-02-24 6 1 3
2007-02-25 5 5 6
2007-02-26 5 8 7
2007-02-27 5 8 7
設定
dti = pd.date_range('2007-02-10', '2007-03-10', freq='D')
df = pd.DataFrame(np.random.randint(1, 10, (len(dti), 3)),
index=dti, columns=list('ABC'))
print(df)
# Output:
A B C
2007-02-10 4 5 6
2007-02-11 2 7 5
2007-02-12 1 2 2
2007-02-13 4 6 1
2007-02-14 6 2 6
2007-02-15 8 4 4
2007-02-16 1 7 7
2007-02-17 3 8 5
2007-02-18 2 1 1
2007-02-19 6 10 7
2007-02-20 4 8 2
2007-02-21 2 3 3
2007-02-22 5 5 1
2007-02-23 7 2 5
2007-02-24 6 1 3
2007-02-25 5 5 6
2007-02-26 5 8 7
2007-02-27 5 8 7
2007-02-28 2 6 4
2007-03-01 7 4 7
2007-03-02 4 1 6
2007-03-03 2 1 5
2007-03-04 4 8 6
2007-03-05 7 6 6
2007-03-06 3 2 1
2007-03-07 2 3 6
2007-03-08 7 7 3
2007-03-09 5 6 8
2007-03-10 3 4 7
uj5u.com熱心網友回復:
你可以嘗試這樣的事情:
random.seed(1)
df = pd.DataFrame({'Date':[random.choice(['2007-02','2007-03','2007-04','2007-05']) for x in range(100)],
'col1':[random.choice(["a", "b", "c", "d", "e", "f", "g"]) for x in range(100)],
'col2':[random.choice(range(10)) for x in range(100)]})
df.loc[df.Date=="2007-02",:][::-1][1:11]
輸出:
| 日期 | 第 1 列 | 列2 | |
|---|---|---|---|
| 95 | 2007-02 | C | 5 |
| 86 | 2007-02 | d | 8 |
| 81 | 2007-02 | 乙 | 3 |
| 73 | 2007-02 | 乙 | 9 |
| 67 | 2007-02 | 乙 | 2 |
| 65 | 2007-02 | G | 1 |
| 60 | 2007-02 | F | 7 |
| 58 | 2007-02 | 一種 | 5 |
| 50 | 2007-02 | 一種 | 2 |
| 42 | 2007-02 | F | 9 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347394.html
上一篇:在R中回圈組合兩個資料框的列
