首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python中进行了一些更改后复制行

问在Python中进行了一些更改后复制行
EN

Stack Overflow用户
提问于 2020-02-29 11:23:27
回答 1查看 206关注 0票数 1

我遇到了一个如何在Python中使用循环函数复制行的问题。我有一个这样的数据集(这是一个熊猫数据框):

代码语言:javascript
复制
    userId  period  Date    
0   41851   4       1/4/2015    
1   13575   1       1/4/2015    

我想复制第一行3次,每次对于原始行,period列需要减1。直到原始行的period是1。而且每次当我复制它时,我想在日期上添加1个月。所以结果会是这样的:

代码语言:javascript
复制
    userId  period  Date    
0   41851   1       1/4/2015
1   41851   1       2/4/2015
2   41851   1       3/4/2015
3   41851   1       4/4/2015    
4   13575   1       1/4/2015    

有人知道怎么做吗?谢谢!

EN

回答 1

Stack Overflow用户

发布于 2020-02-29 16:37:18

想法是用Index.repeat和DataFrame.loc重复行,然后用this solution按GroupBy.cumcount添加日期,最后用Series.dt.strftime更改日期时间的格式

代码语言:javascript
复制
def combine64(years, months=1, days=1, weeks=None, hours=None, minutes=None,
              seconds=None, milliseconds=None, microseconds=None, nanoseconds=None):
    years = np.asarray(years) - 1970
    months = np.asarray(months) - 1
    days = np.asarray(days) - 1
    types = ('<M8[Y]', '<m8[M]', '<m8[D]', '<m8[W]', '<m8[h]',
             '<m8[m]', '<m8[s]', '<m8[ms]', '<m8[us]', '<m8[ns]')
    vals = (years, months, days, weeks, hours, minutes, seconds,
            milliseconds, microseconds, nanoseconds)
    return sum(np.asarray(v, dtype=t) for t, v in zip(types, vals)
               if v is not None)

def year(dates):
    "Return an array of the years given an array of datetime64s"
    return dates.astype('M8[Y]').astype('i8') + 1970

def month(dates):
    "Return an array of the months given an array of datetime64s"
    return dates.astype('M8[M]').astype('i8') % 12 + 1

def day(dates):
    "Return an array of the days of the month given an array of datetime64s"
    return (dates - dates.astype('M8[M]')) / np.timedelta64(1, 'D') + 1

代码语言:javascript
复制
df['Date'] = pd.to_datetime(df['Date'])

df1 = df.loc[df.index.repeat(df['period'])]
g = df1.groupby(level=0).cumcount()

start = df1['Date'].values
df1['Date'] = combine64(year(start), months=month(start) + g, 
                           days=day(start))
df1['period'] = 1
df1 = df1.reset_index(drop=True)

df1['Date'] = df1['Date'].dt.strftime('%m/%d/%Y')
print (df1)
   userId  period        Date
0   41851       1  01/04/2015
1   41851       1  02/04/2015
2   41851       1  03/04/2015
3   41851       1  04/04/2015
4   13575       1  01/04/2015
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60461712

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档