根据其他列向 Panda 数据框添加新列

py *_* me 4 regex dataframe python-3.x pandas

我正在尝试向 Panda 数据集添加一个新列。这个新列 df['Year_Prod'] 派生自另一个 df['title'] 我从中提取年份。

数据示例:

country    designation     title
Italy      Vulkà Bianco    Nicosia 2013 Vulkà Bianco (Etna)         
Portugal   Avidagos        Quinta dos Avidagos 2011 Avidagos Red (Douro)      
Run Code Online (Sandbox Code Playgroud)

代码:

import re

import pandas as pd

df=pd.read_csv(r'test.csv', index_col=0)

df['Year_Prod']=re.findall('\\d+', df['title'])

print(df.head(10))
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

 File "C:\Python37\lib\site-packages\pandas\core\frame.py", line 3119, in __setitem__self._set_item(key, value)

  File "C:\Python37\lib\site-packages\pandas\core\frame.py", line 3194, in _set_item value = self._sanitize_column(key, value)

  File "C:\Python37\lib\site-packages\pandas\core\frame.py", line 3391, in _sanitize_column value = _sanitize_index(value, self.index, copy=False)

  File "C:\Python37\lib\site-packages\pandas\core\series.py", line 4001, in _sanitize_index raise ValueError('Length of values does not match length of ' 'index')

**ValueError: Length of values does not match length of index**
Run Code Online (Sandbox Code Playgroud)

请让我知道您对此的看法,谢谢。

Vai*_*ali 5

您可以使用熊猫str.extract

df['Year_Prod']= df.title.str.extract('(\d{4})')

    country     designation     title                                          Year_Prod
0   Italy       Vulkà Bianco    Nicosia 2013 Vulkà Bianco (Etna)                2013
1   Portugal    Avidagos        Quinta dos Avidagos 2011 Avidagos Red (Douro)   2011
Run Code Online (Sandbox Code Playgroud)

编辑:正如@Paul H. 在评论中所建议的,您的代码不起作用的原因是 re.findall 需要一个字符串,但您正在传递一个系列。它可以使用 apply 来完成,其中在每一行,传递的值是一个字符串,但没有多大意义,因为 str.extract 更有效。

df.title.apply(lambda x: re.findall('\d{4}', x)[0])
Run Code Online (Sandbox Code Playgroud)

  • 可能值得解释一下,`re.findall` 需要一个字符串作为它的第二个参数,但 OP 却通过了 `pandas.Series`。此外,OP 应该知道标准库中的函数通常不会接受 pandas 对象 (3认同)

WeN*_*Ben 5

pandasfindall也有

df.title.str.findall('\d+').str[0]
Out[239]: 
0    2013
1    2011
Name: title, dtype: object

#df['Year_Prod']= df.title.str.findall('\d+').str[0] from pygo
Run Code Online (Sandbox Code Playgroud)