如何保持Pandas中前一行的运行总数?

2024-04-18 21:07:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学习Python/Pandas的同时,正在使用《纽约时报》管理的COVID19逐县数据。数据集使用了一个运行总数,我正在尝试为“新案例”创建一个额外的列。以下是我尝试过的:

import pandas as pd
import requests 

df = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19- 
data/master/us-counties.csv")
df1 = df.loc[(df['state'] == 'New Hampshire') & (df['county'] == 
'Rockingham')]

这是df1的一个示例输出:

^{tb1}$

现在我要做的是为df1创建“新案例”列。以下是我尝试过的:

df1['new cases'] = df1['cases'].diff()

这将返回错误:

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc (can't post the rest here because stackoverflow thinks it's code and won't submit otherwise)...

理想情况下,我想把所有的县分开,但我喜欢在我还在学习的时候把大问题分解成小问题,我似乎不明白为什么这样的事情不起作用