我有一個 Excel 文件,我想讀取該 Excel 文件中的特定列,我使用以下代碼執行此操作:import pandas as pdimport xlrdfile_location = input('Where is the file located? Please input the file path here. ')column = input('In what column is the code? ')code_array = pd.read_excel(file_location, usecols=column)for i in code_array: print(code_array)并且該代碼在控制臺中打印出該列的內容?,F在,該列的文本如下:12345 - Description。我只想提取號碼,我該怎么做?我想過使用 [0:5] 中的子字符串或將數據轉換為字符串數組,但我不確定該怎么做。
1 回答

慕碼人8056858
TA貢獻1803條經驗 獲得超6個贊
如果數字每次都是 5 位長,您可以使用 lambda 快速創建一個子字符串。
code_array["number_column"] = code_array["YourColumnNameHere"].apply(lambda x: str(x)[:5])
如果每次的長度不一樣,但是位置都一樣,可以拆分成一個字符串數組,然后訪問第一個元素:
code_array["number_column"] = code_array["YourColumnNameHere"].apply(lambda x: str(x).split()[0])
讓我知道這是否解決了您的問題,否則我們將需要使用正則表達式。注意將 YourColumnNameHere 更改為與數據框中的列同名。
添加回答
舉報
0/150
提交
取消