我想切开的列是这样的。
{'name':['A', 'B', 'C'], 'location':['(x=31.33 y=19.98)', '(x=9.33 y=6.98)', '(x=-12.67 y=-30.02)']}
我想拉出 x
和 y
值到他们自己的列中,看起来像这样。
{'name':['A', 'B', 'C'], 'x':[31.33, 9.33, -12.67], 'y':[19.98,6.98,-30.02]}
我想我需要做一些切片,但不知道该怎么做。谢谢。
你可以使用regex来解决这个问题。
import re
d = {'name':['A', 'B', 'C'], 'location':['(x=31.33 y=19.98)', '(x=9.33 y=6.98)', '(x=-12.67 y=-30.02)']}
x = [re.search(r'x=((?:\-)?\d+(?:\.\d+))', x).group(1) for x in d['location']]
y = [re.search(r'y=((?:\-)?\d+(?:\.\d+))', x).group(1) for x in d['location']]
res = {
'name': d['name'],
'x': list(map(float, x)),
'y': list(map(float, y))
}
print(res)
# {'name': ['A', 'B', 'C'], 'x': [31.33, 9.33, -12.67], 'y': [19.98, 6.98, -30.02]}
如果你很确定你的数据总是遵循这种模式, 你可以将上面的regex简化为:
x = [re.search(r'x=(.*) ', x).group(1) for x in d['location']]
y = [re.search(r'y=(.*)\)', x).group(1) for x in d['location']]
你可以用re库(和列表理解)更优雅地做到这一点。
import re
data = {'name':['A', 'B', 'C'], 'location':['(x=31.33 y=19.98)', '(x=9.33 y=6.98)', '(x=-12.67 y=-30.02)']}
data['x'] = [float(re.split("=| |\)", i)[1]) for i in data['location']]
data['y'] = [float(re.split("=| |\)", i)[3]) for i in data['location']]
del(data['location'])
data
>>> {'name': ['A', 'B', 'C'],
'x': [31.33, 9.33, -12.67],
'y': [19.98, 6.98, -30.02]}
这里有一个解决方案。
start = {
'name':['A', 'B', 'C'],
'location':['(x=31.33 y=19.98)',
'(x=9.33 y=6.98)',
'(x=-12.67 y=-30.02)']
}
xList = []
yList = []
for string in start['location']:
splitted = string[1:-1].split(" ")
x = splitted[0].split("=")[1]
y = splitted[1].split("=")[1]
xList.append(x)
yList.append(y)
end = {
'name' : start['name'],
'x' : xList,
'y' : yList
}
print(end)
你也可以使用regex来匹配字符串中的模式(文件, regex表达式测试网站)
EDIT :
这里有一个用regex的解决方案,更优雅。
import re
start = {
'name':['A', 'B', 'C'],
'location':['(x=31.33 y=19.98)',
'(x=9.33 y=6.98)',
'(x=-12.67 y=-30.02)']
}
end = {
'name' : start['name'],
'x' : [],
'y' : []
}
for string in start['location']:
checkNumber = re.compile("([\d]+[.]*[\d]*)")
numbers = checkNumber.findall(string)
end['x'].append(numbers[0])
end['y'].append(numbers[1])
print(end)
你可以测试一下这个regex 此处
你需要对字符串进行解析。
import pandas as pd
import re
t = {'name':['A', 'B', 'C'], 'location':['(x=31.33 y=19.98)', '(x=9.33 y=6.98)', '(x=-12.67 y=-30.02)']}
res = pd.DataFrame({'name':t['name'], 'x':[float(re.search("\(x=(.*) y", i).group(1)) for i in t['location']], 'y':[float(re.search("y=(.*)\)", i).group(1)) for i in t['location']]})
最简单的方法是用 "pandas.Series.str.extract() "创建新的列,即:
df = pd.DataFrame(["{'name':['A', 'B', 'C'], 'location':['(x=31.33 y=19.98)', '(x=9.33 y=6.98)', '(x=-12.67 y=-30.02)']}"])
df.location.str.extract(r'x=(?P<x>[0-9.-]+) y=(?P<y>[0-9.-]+)', expand=True)
即:"输出"。
x y
0 31.33 19.98
1 9.33 6.98
2 -12.67 -30.02
如果你需要将新的列保存在现有的数据框架中,你可以使用 "pandas.Series.str.extract() "来创建新的列。pd.concat()
,即..:
df = pd.concat([df, df.location.str.extract(r'x=(?P<x>[0-9.-]+) y=(?P<y>[0-9.-]+)', expand=True)], axis=1)