首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在派生自另一列的Pandas中添加列

问如何在派生自另一列的Pandas中添加列
EN

Stack Overflow用户
提问于 2021-07-29 00:21:52
回答 1查看 34关注 0票数 0

我需要计算工作hs (花费的时间)的总和,然后对它们进行分组,但我在第一步中遇到了困难(转换列并提取值)

下面是一个示例:

代码语言:javascript
复制
df = pd.read_excel("Time spent week.xls")

df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 18 entries, 0 to 17
Data columns (total 7 columns):
 #   Column             Non-Null Count  Dtype         
---  ------             --------------  -----         
 0   Task title         18 non-null     object        
 1   User               18 non-null     object        
 2   Date               18 non-null     datetime64[ns]
 3   Time spent         18 non-null     object        
 4   Project or folder  18 non-null     object        
 5   Category           15 non-null     object        
 6   DateYW             18 non-null     object        
dtypes: datetime64[ns](1), object(6)
memory usage: 1.1+ KB

耗时信息格式为--> 01:00:00

我试过了,但我不能理解这个问题

代码语言:javascript
复制
def strip2(val):
    new_val = val.split(sep=':', maxsplit=1)
    return float(new_val)
df["Time spent2"] = df["Time spent"].apply(strip2)
代码语言:javascript
复制
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-65-4f94c4e06b06> in <module>
      2     new_val = val.split(sep=':', maxsplit=1)
      3     return float(new_val)
----> 4 df["Time spent2"] = df["Time spent"].apply(strip2)

~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
   4136             else:
   4137                 values = self.astype(object)._values
-> 4138                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   4139 
   4140         if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()

<ipython-input-65-4f94c4e06b06> in strip2(val)
      1 def strip2(val):
----> 2     new_val = val.split(sep=':', maxsplit=1)
      3     return float(new_val)
      4 df["Time spent2"] = df["Time spent"].apply(strip2)

AttributeError: 'datetime.time' object has no attribute 'split'
EN

回答 1

Stack Overflow用户

发布于 2021-07-29 20:25:00

使用to_datetime函数,指定与您的数据匹配的格式。

代码语言:javascript
复制
df['Time spent'] =  df.to_datetime(df['Time spent'], format='%H:%M:%S')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68564033

复制
相关文章

相似问题

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