Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何替换对象特征中数字之间的文本_Python_Pandas_Numpy - Fatal编程技术网

Python 如何替换对象特征中数字之间的文本

Python 如何替换对象特征中数字之间的文本,python,pandas,numpy,Python,Pandas,Numpy,我有一个对象特性“出版年份”,我想把它转换成数字类型。该功能包含2009、2018、1995等值。。。DK某物。。。我想我需要找到特性中的所有字符串,并用一些默认值替换它们,但我不知道如何实际做到这一点 我试过: data = data['Year-Of-Publication'].astype(int) ……这引起: ValueError:基数为10的int()的文本无效:“DK发布” 公司 我们将不胜感激。谢谢 编辑: 该属性看起来像: books['Year-Of-Publication

我有一个对象特性“出版年份”,我想把它转换成数字类型。该功能包含2009、2018、1995等值。。。DK某物。。。我想我需要找到特性中的所有字符串,并用一些默认值替换它们,但我不知道如何实际做到这一点

我试过:

data = data['Year-Of-Publication'].astype(int)
……这引起:

ValueError:基数为10的int()的文本无效:“DK发布” 公司

我们将不胜感激。谢谢

编辑:

该属性看起来像:

books['Year-Of-Publication'].head()

0    2002
1    2001
2    1991
3    1999
4    1999
Name: Year-Of-Publication, dtype: object

我想将其转换为数字类型,但问题是它也包含字符串,例如值“DK Publishing Inc.”

指定允许值的范围,在本例中为有效年份的范围。不在该范围内的所有值都可以替换为您选择的默认值:

import pandas as pd

# Just some made up data
df = pd.DataFrame({'year-of-publication': [2009, 2018, 1995, 'DK-1235', 2005, 'ssjdk']})

# Select all rows that don't have valid years, in this case ranging from 1900 to 2019
# and set them to your default value, in this case 2000
df.loc[~df['year-of-publication'].isin(list(range(1900,2020)))] = 2000 
print(df)

使用
pandas.to_numeric
fillna

import pandas as pd

s = pd.Series([2009, 2018, 1995, 'DK-Something'])
pd.to_numeric(s, 'coerce').fillna(-1, downcast = 'infer')
输出:

0    2009
1    2018
2    1995
3      -1
dtype: int64

此处,
fillna
(即
-1
)的值是您选择的默认替换值。

您可以添加一些代码,说明您拥有哪些数据以及您想要哪些输出?coerse和downcast='infer'是什么意思?@StanislavJirák抱歉输入错误。它是
强制
。意思是说
downcast='infer'
意味着在填充系列后,
pandas
将尝试将数据类型更改为尽可能最小的数据类型。谢谢。伟大的解决方案!