如何从数据框中获取字符串

2024-04-26 22:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用两个参数定义一个函数:df(dataframe)和一个整数(employerID)作为我的参数。此函数将返回雇主的全名。你知道吗

如果给定的ID不属于任何员工,我想返回字符串“UNKNOWN”/如果没有给出中间名,只返回“LAST,FIRST”。/如果只给出中间的首字母,则返回格式为“LAST,FIRST M.”的全名,中间的首字母后跟“.”。你知道吗

def getFullName(df, int1):
    df = pd.read_excel('/home/data/AdventureWorks/Employees.xls')
    newdf = df[(df['EmployeeID'] == int1)]
    print("'" + newdf['LastName'].item() + "," + " " + newdf['FirstName'].item() + " " + newdf['MiddleName'].item() + "." + "'")

getFullName('df', 110)

我写了这段代码,但遇到了两个问题: 1) 如果我不在df周围加引号,它会给我一个错误消息,但我只想把数据帧作为参数,而不是字符串。你知道吗

2)此代码不能处理没有中间名的人。你知道吗

对不起,我以前pd.read\U表格读取无法访问的excel文件。我知道如果没有excel文件,你很难测试代码,如果有人让我知道如何创建一个带有列名的随机数据框,我会继续更改它。谢谢你


Tags: 函数字符串代码dfread参数itemexcel
1条回答
网友
1楼 · 发布于 2024-04-26 22:35:17

我为此创建了一些假数据:

           EmployeeID FirstName LastName MiddleName
0          0         a        a          a
1          1         b        b          b
2          2         c        c          c
3          3         d        d          d
4          4         e        e          e
5          5         f        f          f
6          6         g        g          g
7          7         h        h          h
8          8         i        i          i
9          9         j        j       None

EmployeeID9没有中间名,但其他人都有。我的方法是把逻辑分成两部分。第一,当你找不到EmployeeID的时候。第二个负责打印员工姓名。第二部分还应该有两组逻辑,一组控制员工是否有中间名,另一组控制他们是否有中间名。你可能会将很多这部分合并成单行语句,但你可能会牺牲清晰度。你知道吗

我还从函数中删除了pd.read_excel调用。如果您想将数据帧传递给函数,那么应该为其创建数据帧。你知道吗

def getFullName(df, int1):
   newdf = df[(df['EmployeeID'] == int1)]

   # if the dataframe is empty, then we can't find the give ID
   # otherwise, go ahead and print out the employee's info
   if(newdf.empty):
       print("UNKNOWN")
       return "UNKNOWN"
   else:
       # all strings will start with the LastName and FirstName
       # we will then add the MiddleName if it's present
       # and then we can end the string with the final '
       s = "'" + newdf['LastName'].item() + ", " +newdf['FirstName'].item()
       if (newdf['MiddleName'].item()):
           s = s + " " + newdf['MiddleName'].item() + "."
       s = s + "'"
       print(s)
       return s

我有一个返回值的函数,以防您想进一步操作字符串。但那只是我。你知道吗

如果你运行getFullName(df, 1),你应该得到'b, b b.'。对于getFullName(df, 9)你应该得到'j, j'。你知道吗

因此,总的来说,应该是:

df = pd.read_excel('/home/data/AdventureWorks/Employees.xls')
getFullName(df, 1)  #outputs 'b, b b.'
getFullName(df, 9)  #outputs 'j, j'
getFullName(df, 10) #outputs UNKNOWN

虚假数据:

d = {'EmployeeID' : [0,1,2,3,4,5,6,7,8,9],
     'FirstName' : ['a','b','c','d','e','f','g','h','i','j'],
     'LastName' : ['a','b','c','d','e','f','g','h','i','j'],
     'MiddleName' : ['a','b','c','d','e','f','g','h','i',None]}
df = pd.DataFrame(d)

相关问题 更多 >