Pandas/python,在数据帧中使用列,使用d

2024-09-04 18:50:10 发布

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

我目前正在为一个Python/Pandas数据科学项目工作。我正在查看的数据有一个日期列,其中的日期如下所示:2016-07-16。数据类型也是一个对象。我要做的是遍历每个日期并从该行中提取数据。现在,有些行可能具有相同的日期,因为在该日期发生了两次独立的攻击。(我正在查看恐怖主义数据。)我目前所做的工作如下:

dates = []
start = 0;
while start < 300: 
    date = data.iat[start, 1]
    dates.append(date)
    start += 1

这会让我得到我想要的东西。但是,我有两个问题,start变量被设置为0,但是我不能转到365,因为正如我所说的,每个日期可能有多个攻击。所以一年可能有400起袭击。有没有办法可以在2016-12-31或2017-01-01结束数据收集?基本上,有没有一种方法可以快速确定每年的攻击次数?谢谢你的帮助!在

哦,我要说的是我在尝试类似的事情:

^{pr2}$

或者

data['Date']) + timedelta(days=1)

将一个添加到结束于该年的日期。没有得到我想要的,而且每天可能有不止一个条目。在

为了进一步解释,我可以这样解释:

Date            Deaths     Country 
2002-01-01         2         India 
2002-01-02         0         Pakistan
2001-01-02         1         France

数据大约有2万个点,我需要在每年年底找到一个阻止它的方法。这是我的主要问题。我不能去365,因为全世界可能在同一天发生多起恐怖袭击。在


Tags: 数据项目对象方法pandasdatadate科学
2条回答

处理这个问题的另一种方法是查字典

# Get column with the dates 
dates = df.iloc[:,0].values
year_attacks = {}
for date in dates:
    # Get year from the date
    year=str(date).split('-')[0]
    # If year is already in the dictionary increase number of attacks by 1
    if year in year_attacks:
       year_attacks[year]=year_attacks[year]+1
    # Else create new key
    else:
       year_attacks[year]=1

IMO无需添加新栏:

In [132]: df
Out[132]:
        Date  Deaths   Country
0 2002-01-01       2     India
1 2002-01-02       0  Pakistan
2 2001-01-02       1    France

In [217]: df.groupby(df.Date.dt.year)['Deaths'].sum()
Out[217]:
Date
2001    1
2002    2
Name: Deaths, dtype: int64

或者:

^{pr2}$

您可以随时访问DateTime列的不同部分(年、月、日、工作日、小时等):

In [137]: df.Date.dt.year
Out[137]:
0    2002
1    2002
2    2001
Name: Date, dtype: int64

In [138]: df.Date.dt.
df.Date.dt.ceil             df.Date.dt.freq             df.Date.dt.microsecond      df.Date.dt.strftime         df.Date.dt.weekday
df.Date.dt.date             df.Date.dt.hour             df.Date.dt.minute           df.Date.dt.time             df.Date.dt.weekday_name
df.Date.dt.day              df.Date.dt.is_month_end     df.Date.dt.month            df.Date.dt.to_period        df.Date.dt.weekofyear
df.Date.dt.dayofweek        df.Date.dt.is_month_start   df.Date.dt.nanosecond       df.Date.dt.to_pydatetime    df.Date.dt.year
df.Date.dt.dayofyear        df.Date.dt.is_quarter_end   df.Date.dt.normalize        df.Date.dt.tz
df.Date.dt.days_in_month    df.Date.dt.is_quarter_start df.Date.dt.quarter          df.Date.dt.tz_convert
df.Date.dt.daysinmonth      df.Date.dt.is_year_end      df.Date.dt.round            df.Date.dt.tz_localize
df.Date.dt.floor            df.Date.dt.is_year_start    df.Date.dt.second           df.Date.dt.week

相关问题 更多 >