簡體   English   中英

如何在 sqlite python 中提取字符串的數字部分

[英]How to extract the numeric part of a string in sqlite python

我正在研究 IMDB 數據集,我的電影表記錄如下

import sqlite3
import pandas as pd
conn=sqlite3.connect('Db-IMDB.db')
result1=pd.read_sql_query('select year from Movie order by year',conn)
print(type(result1))
print(result1)

我得到 output 如下圖所示

<class 'pandas.core.frame.DataFrame'>
           year
0          1931
1          1936
2          1936
3          1936
4          1939
...         ...
3470    IV 2011
3471    IV 2017
3472     V 2015
3473    VI 2015
3474  XVII 2016

[3475 rows x 1 columns]

年份列的數據類型是文本。

那么我能否知道如何只獲取數據的數字部分,以便我可以進行像 % 這樣的數字運算,以便在 sqlite 中獲得閏年?

使用正則表達式:

def findNum(x):
    return re.findall(r'[0-9]+',x)[0]


df = pd.DataFrame({
    'a':['IV 2014','2015','v 2016']
    })

#float just for typecasting so that use can do numeric operations
print(df['a'].apply(findNum).apply(float))  

Output:

0    2014
1    2015
2    2016
Name: a, dtype: float64
[Finished in 2.4s]

如果非數字是羅馬數字和數字組件左側的空格,如示例所示,那么您可以使用 SQLite 的ltrim function:

sqlite> select ltrim("XVI   1955", "CDILMVX ");
1955

您可能需要考慮更全面的要丟棄的字符列表,例如

"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_ "

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM