我的数据在 Excel 中看起来像:(字符串和数字的组合)

Time Spent
3600
0
None
1800
0

我试过下面的代码

if (df['Time Spent']=='None').all():
 df['Time Spent'] = 0
else:
 df['Time Spent'] = df['Time Spent'].astype('int')/3600


Index([u'Issue Key', u'Issue Id', u'Summary', u'Assignee', u'Priority',
       u'Issue Type', u'Status', u'Tag', u'Original Estimate', u'Time Spent',
       u'Resolution Date', u'Created Date'],
      dtype='object')
Traceback (most recent call last):
  File "dashboard_migration_graph_Resolved.py", line 60, in <module>
    df['Time Spent'] = df['Time Spent'].astype('int')/3600
  File "/usr/lib64/python2.7/site-packages/pandas/util/_decorators.py", line 118, in wrapper
    return func(*args, **kwargs)


  File "pandas/_libs/lib.pyx", line 854, in pandas._libs.lib.astype_intsafe
  File "pandas/_libs/src/util.pxd", line 91, in util.set_value_at_unsafe
ValueError: invalid literal for long() with base 10: 'None'

最佳答案

使用 to_numeric errors='coerce' 将所有非数字转换为缺失值,因此在除法之前添加 Series.fillna :

df['Time Spent'] = pd.to_numeric(df['Time Spent'], errors='coerce').fillna(0)/3600
print (df)
   Time Spent
0         1.0
1         0.0
2         0.0
3         0.5
4         0.0

如果需要 None 像缺失值一样只删除 fillna - 而不是 None 得到缺失值 NaN ,那么多列也是可能的:
df['Time Spent'] = pd.to_numeric(df['Time Spent'], errors='coerce')/3600
print (df)
   Time Spent
0         1.0
1         0.0
2         NaN
3         0.5
4         0.0

关于python - 从 Dataframe 对象过滤字符串和整数值 -python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56922160/

10-14 19:18