如何使用 Python 从 excel 中的列中获取子字符串?

How to take a substring from a column in excel using Python?

我有一个 Excel 文件,我想读取该 Excel 文件中的特定列,我使用以下代码执行此操作:

import pandas as pd
import xlrd

file_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)

并且该代码在控制台中打印出该列的内容。现在,该列的文本如下:12345 - Description。我只想提取号码,我该怎么做?我想过使用 [0:5] 中的子字符串或将数据转换为字符串数组,但我不确定该怎么做。

如果数字每次都是 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 更改为与数据框中的列相同的名称。