Python- Pandas : extract a number from column into new column

标签 python pandas

我一直在 python 中使用 pandas 来提取信息。我的数据框的一列中有以下标题:

   0
In & Out (1997)
Simple Plan, A (1998)
Retro Puppetmaster (1999)
Paralyzing Fear: The Story of Polio in America, A (1998)
Old Man and the Sea, The (1958)
Body Shots (1999)
Coogan's Bluff (1968)
Seven Samurai (The Magnificent Seven) (Shichinin no samurai) (1954)
Search for One-eye Jimmy, The (1996)
Funhouse, The (1981)

我想将这些标题的年份放入一个新专栏中。我遇到的问题是,如果我将“(”作为分隔符进行拆分,如您在第 8 行中看到的那样,它会在那里拆分。那么我如何在 (yyyy) 处拆分以形成该年份的新列看起来像这样?

     0                 1
In & Out              1997
Simple Plan, A        1998
Retro Puppetmaster    1999 
Paralyzing Fear:...   1998
Old Man and the S...  1958
Body Shots            1999
Coogan's Bluff        1968 
Seven Samurai (T...   1954
Search for One-ey...  1996
Funhouse, The         1981

最佳答案

您可以使用展开:

df['year'] = df.iloc[:,0].str.extract('\((\d{4})\)'',expand=False)

df
Out[381]: 
                                                   0  year
0                                    In & Out (1997)  1997
1                              Simple Plan, A (1998)  1998
2                          Retro Puppetmaster (1999)  1999
3  Paralyzing Fear: The Story of Polio in America...  1998
4                    Old Man and the Sea, The (1958)  1958
5                                  Body Shots (1999)  1999
6                              Coogan's Bluff (1968)  1968
7  Seven Samurai (The Magnificent Seven) (Shichin...  1954
8               Search for One-eye Jimmy, The (1996)  1996
9                               Funhouse, The (1981)  1981

关于Python- Pandas : extract a number from column into new column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44464118/

相关文章:

python - 在 Python 中为数千个大表进行外部连接

python - 打印数据框名称

python - Dijkstra 的算法概念和编码问题

python - python 中轮询套接字的问题

python-3.x - 在没有 Agg 的情况下在多个列上透视 Pandas 数据框

python - 根据上一行的输出分配值

pandas - 更改数据帧索引中的日期格式时出错

python - PyTorch 加载 "\lib\site-packages\torch\lib\shm.dll"或其依赖项之一时出错

python - 当本地是 Django 1.7/Postgres 9.3 时,我应该如何调试在 Django 1.3/Postgres 8.4 的服务器上运行的应用程序?

用于重复字符串的python正则表达式