python - 从Dataframe对象过滤字符串和整数值-python

标签 python excel pandas

I want to implement operation on excel file in one column that column has string and integer data but that column is object type

我的数据在 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

Error which I am getting

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/

相关文章:

python - 在 pandas DataFrame 上定期选择列

python - 为什么首先分配给变量时 pandas.dataframe.groupby 更快?

excel - 指数回归 : Translate mathematical notation to Excel syntax

c# - 无法创建 VSTO Excel 工作簿项目

python - 在 groupby 聚合之后指定列顺序

python - Python 中错误的 if-else 情况

python - 在redis中存储带或不带散列的键值对

excel - 使用系统时间每 30 秒保存一次 Excel 文件

python - 如何检查 Pandas 数据框中是否存在具有特定列值的行

pandas - 在 Pandas 数据框中创建一个包含 bool 列组合计数的方阵