[英]How to invoke each function in a row in a pandas column by an argument at the respective index?
[英]A pandas dataframe column to pass as an argument of row level function to apply each value of the column to its respective row
![在此处输入图像描述][1]
我有一个奇怪的要求,即添加类似于以下 oracle 查询的列以应用于 python dataframe。 A pandas dataframe 列作为行级 function 的参数传递,以将列的每个值应用于其各自的行。
select employee_id, first_name, last_name, substr(first_name, employee_id/employee_id, 3) test1 from hr.EMPLOYEES
结果已附在下面的 csv 文件中。 我想添加一个新列。 所以我写了我的 pandas 声明如下
EMPLOYEE.assign(test1=EMPLOYEE.FIRST_NAME.str.slice(EMPLOYEE.EMPLOYEE_ID.apply(lambda x: x/x),4))
在此代码中,我在 EMPLOYEE.FIRST_NAME 列的切片 function 内使用 EMPLOYEE.EMPLOYEE_ID。
我的意图是如果我们认为这是一个变量
FIRST_NAME="Steven"
EMPLOYEE_ID=100
FIRST_NAME[int(EMPLOYEE_ID/EMPLOYEE_ID):4]
output 是'tev'
我没有得到 substring,而是得到了 NaN。 我的 Python output 如下
https://i.stack.imgur.com/uZN8x.png
以下是来自 SQL 查询的 output。
EMPLOYEE_ID FIRST_NAME LAST_NAME TEST1
0 100 Steven King Ste
1 101 Neena Kochhar Nee
2 102 Lex De Haan Lex
3 103 Alexander Hunold Ale
4 104 Bruce Ernst Bru
5 105 David Austin Dav
6 106 Valli Pataballa Val
7 107 Diana Lorentz Dia
8 108 Nancy Greenberg Nan
9 109 Daniel Faviet Dan
10 110 John Chen Joh
11 111 Ismael Sciarra Ism
12 112 Jose Manuel Urman Jos
13 113 Luis Popp Lui
我们可以通过创建一个新列来做到这一点,但是,就像在 SQL 中一样,我们可以直接做到这一点。 我期待通过 pandas 得到同样的结果。 请帮助我。
我的预期 output 与上面相同。 但是,我正在编写一个通用脚本,将 SQL 查询转换为 pandas dataframe。 我被困在实现这样的场景中,其中有一列作为行级 function 的参数传递。
尝试:
res = df[['EMPLOYEE_ID', 'FIRST_NAME', 'LAST_NAME']].assign(pre=df['FIRST_NAME'].str[:3])
print(res)
Output
EMPLOYEE_ID FIRST_NAME LAST_NAME pre
0 100 Steven King Ste
1 101 Neena Kochhar Nee
2 102 Lex De Haan Lex
3 103 Alexander Hunold Ale
4 104 Bruce Ernst Bru
5 105 David Austin Dav
6 106 Valli Pataballa Val
7 107 Diana Lorentz Dia
8 108 Nancy Greenberg Nan
9 109 Daniel Faviet Dan
10 110 John Chen Joh
11 111 Ismael Sciarra Ism
12 112 Jose Manuel Urman Jos
13 113 Luis Popp Lui
要将它与str.slice一起使用,请执行以下操作:
res = df[['EMPLOYEE_ID', 'FIRST_NAME', 'LAST_NAME']].assign(pre=df['FIRST_NAME'].str.slice(stop=3))
其中,停止是:
stop int,可选 Stop position 用于切片操作。
基本上一次迭代一个字符并在 position 3 (不包括在内)中停止。
df[['EMPLOYEE_ID', 'FIRST_NAME', 'LAST_NAME']].apply(lambda i: i.FIRST_NAME[int(i.EMPLOYEE_ID/i.EMPLOYEE_ID):4], axis=1)
以上为我解答。 但它比另一个慢
%timeit EMPLOYEE.apply(lambda i: i.FIRST_NAME[int(i.EMPLOYEE_ID/i.EMPLOYEE_ID):3], axis=1)
每个循环 1.38 毫秒 ± 58.8 微秒(平均值 ± 标准偏差。7 次运行,每次 1000 次循环)
%timeit EMPLOYEE[['EMPLOYEE_ID', 'FIRST_NAME', 'LAST_NAME']].assign(pre=EMPLOYEE['FIRST_NAME'].str[1:4])
每个循环 948 µs ± 22.9 µs(7 次运行的平均值 ± 标准偏差,每次 1000 个循环)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.