[英]How to use apply in a Pandas dataframe slice to set values of multiple columns
I am trying to use apply function to assign new values to two existing columns in a dataframe slice using a .loc query.我正在尝试使用 apply 函数使用 .loc 查询为数据帧切片中的两个现有列分配新值。
To reproduce - first create a dataframe:要重现 - 首先创建一个数据框:
import re
import panads as pd
data = [[1000, "MSL", "Test string"], [2000, 'AGL', 'other string'], [0, 'AGL', "xxxx SFC-10000ft MSLXXX"]]
df = pd.DataFrame(data=data, columns=['Alt', "AltType",'FreeText'])
Then create the apply function然后创建应用函数
def testapply(row):
try:
match = re.findall("SFC-([0-9]+)FT (MSL|AGL|FL)", row.FreeText)[0]
return (int(match[0]), match[1])
except:
return (0, row.AltType)
When I run当我跑
df.loc[df['Alt']==0, ['Alt', 'AltType']] = df.loc[df['Alt']==0].apply(testapply, axis=1)
I would like to get as a result is:我想得到的结果是:
Alt AltType FreeText
0 1000 MSL Test string
1 2000 AGL other string
2 10000 MSL xxxx SFC-10000ft MSLXXX
but what I end up getting is:但我最终得到的是:
Alt AltType FreeText
0 1000 MSL Test string
1 2000 AGL other string
2 (10000, MSL) (10000, MSL) xxxx SFC-10000FT MSLXXX
Does anyone know how to make this work in one fell swoop?有谁知道如何一举完成这项工作?
只需添加tolist()
df.loc[df['Alt']==0, ['Alt', 'AltType']] = df.loc[df['Alt']==0].apply(testapply, axis=1).tolist()
Let's try Series.str.extract
and use boolean indexing with loc
to replace the values in columns Alt
and AltType
where the column Alt
contains 0
:让我们尝试
Series.str.extract
并使用带有loc
Series.str.extract
替换列Alt
和AltType
中的值,其中Alt
列包含0
:
m = df['Alt'].eq(0)
df.loc[m, ['Alt', 'AltType']] = df.loc[m, 'FreeText'].str.extract(r'(?i)SFC-(\d+)FT\s(MSL|AGL|FL)').values
Alt AltType FreeText
0 1000 MSL Test string
1 2000 AGL other string
2 10000 MSL xxxx SFC-10000ft MSLXXX
Use loc accessor to select relevant Alt
column.使用 loc 访问器选择相关的
Alt
列。 Compute value by extracting digit
from matching FreeText
using regex
通过使用
regex
从匹配的FreeText
提取digit
来计算值
df.loc[df['Alt']==0,'Alt']=df.loc[df['Alt']==0,'FreeText'].str.extract('(\d+)')[0]
Alt AltType FreeText
0 1000 MSL Test string
1 2000 AGL other string
2 10000 AGL xxxx SFC-10000ft MSLXXX
Only change your testapply function to this:仅将您的 testapply 功能更改为:
def testapply(row):
try:
match = re.findall("SFC-([0-9]+)ft (MSL|AGL|FL)", row.FreeText)[0]
print(match)
return (int(match[0]), match[1]).tolist()
except:
return (0, row.AltType)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.