Python 定期获取列中的最新值
以下是我的熊猫数据示例:Python 定期获取列中的最新值,python,pandas,Python,Pandas,以下是我的熊猫数据示例: print(df) country cases date 2020-01-22 Austria 0 2020-01-23 Austria 0 2020-01-24 Austria 0 .... 2020-05-31 Austria 0 2020-06-01 Austria 1 2020-06-02 Austri
print(df)
country cases
date
2020-01-22 Austria 0
2020-01-23 Austria 0
2020-01-24 Austria 0
....
2020-05-31 Austria 0
2020-06-01 Austria 1
2020-06-02 Austria 0
2020-01-22 Belgium 0
2020-01-2 Belgium 0
... ... ..
2020-05-29 United Kingdom 324
2020-05-30 United Kingdom 215
2020-05-31 United Kingdom 113
2020-06-01 United Kingdom 556
2020-06-02 United Kingdom 325
在这里,对于所有不同的国家,我希望得到最后3个“案例”属性的值。
例如,奥地利为[0,1,0],英国为[113556325]
什么是好的pythonic解决方案?如果您想将它们作为数据帧,您可以执行groupby和tail-like: 或者,如果需要类似列表的对象:
(df.sort_values('date')
.groupby('country').apply(lambda x: x['cases'].tail(3).tolist()))
country
Austria [0, 1, 0]
United Kingdom [113, 556, 325]
dtype: object
如果希望将它们作为数据帧,可以执行groupby和tail-like: 或者,如果需要类似列表的对象:
(df.sort_values('date')
.groupby('country').apply(lambda x: x['cases'].tail(3).tolist()))
country
Austria [0, 1, 0]
United Kingdom [113, 556, 325]
dtype: object
也可以在groupby上的日期之前对_值进行排序case@dimitris_ps好的一点,在第一种可能的情况下,我还将_值与国家进行排序,否则结果会在国家之间混淆,更多地用于表示。在第二种情况下,按国家/地区对_值进行排序实际上不会改变结果。由于我需要检索一个列表[[0,1,0],…,[113556325]],我将添加值[:]df.sort_values'date'.groupby'country'.applylambda x:x['cases'].tail3.values[:]。ToList可能还会在groupby日期之前对值进行排序case@dimitris_ps说得好,在第一种可能的情况下,我还将_值与国家进行排序,否则结果会在国家之间混淆,以便于呈现。在第二种情况下,按国家/地区对_值进行排序实际上不会改变结果。由于我需要检索一个列表[[0,1,0],…,[113556325]],我将添加值[:]df.sort_values'date'.groupby'country'.applylambda x:x['cases'].tail3.values[:]tolist
# Read in CSV file-
data = pd.read_csv("data.csv")
# Convert 'date' column -
data.date = pd.to_datetime(data['date'])
# Print last 3 rows for 'cases' attribute-
for x in data.groupby('country'):
print(x[1].iloc[-3:, 2])
'''
3 0
4 1
5 0
Name: cases, dtype: int64
6 0
7 0
Name: cases, dtype: int64
10 113
11 556
12 325
Name: cases, dtype: int64
'''