繁体   English   中英

在 dataframe 中对列进行切片,每行中的字符数不同(Python)

[英]Slicing a column in a dataframe with varied number of characters in each row (Python)

我要切片的列如下所示:

{'name':['A', 'B', 'C'], 'location':['(x=31.33 y=19.98)', '(x=9.33 y=6.98)', '(x=-12.67 y=-30.02)']} 

我想将xy值拉到它们自己的列中,如下所示:

{'name':['A', 'B', 'C'], 'x':[31.33, 9.33, -12.67], 'y':[19.98,6.98,-30.02]} 

我假设我需要做一些切片,但我不确定如何 go 关于它。 谢谢。

您可以为此使用正则表达式:

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]}

如果您非常确定您的数据始终遵循这种模式,您可以将上述正则表达式简化为:

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']]

这是一个解决方案:

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)

您还可以使用正则表达式匹配字符串中的模式(文档正则表达式测试网站

编辑:

这是一个带有正则表达式的解决方案,更优雅:


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)

你可以在这里测试正则表达式

您可以使用 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]}

您需要解析字符串:

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)

Output:

        x       y
0   31.33   19.98
1    9.33    6.98
2  -12.67  -30.02

如果您需要在现有 dataframe 中保存新列,您可以使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM