简体   繁体   English

pandas DataFrame 柱子不规则的零件如何更换或拆除?

[英]How to replace or remove parts from columns in pandas DataFrame which are irregular?

One in my columns in my pandas DataFrame has very irregular expressions.我的pandas DataFrame 里的一个专栏里有很不规则的表达。 I want to remove everything except the coordinates.我想删除除坐标以外的所有内容。 However, I cannot just use the replace or remove function since the parts of what I want to remove are different in each column.但是,我不能只使用替换或删除 function,因为我要删除的部分在每一列中都是不同的。 Is there a way of picking just the part of the strings which I actually want to use?有没有办法只选择我真正想要使用的部分字符串?

One cell looks like this:一个单元格如下所示:

 {'is_geometry': True, 'configuration': 'technologies', 'additional_translations': {}, 'key': 'Map', 'value': '{"type":"FeatureCollection","features":[{"type":"Feature","id":1549869006355,"geometry":{"type":"Point","coordinates":[67.91225703380735,34.69585762863356]},"properties":null}]}', 'map_url': '/en/technologies/view/technologies_1723/map/', 'template': 'raw'}

where the id and the map_url are always different.其中 id 和 map_url 总是不同的。 I would like to only have [67.91225703380735,34.69585762863356] in this example.在这个例子中,我只想 [67.91225703380735,34.69585762863356]。 Further, is there a way of turning the two values around in order that I have [34.69585762863356,67.91225703380735] instead?此外,有没有办法改变这两个值,以便我拥有 [34.69585762863356,67.91225703380735]?

I'm not sure exactly what you want, but assuming your dataframe's column contains dicts that are like your example, this should work:我不确定你到底想要什么,但假设你的数据框列包含与你的示例类似的字典,这应该有效:

import ast
import json
df['nums'] = df.loc[df['tech_map'].notna(), 'tech_map'].astype(str).apply(ast.literal_eval).str['value'].apply(json.loads).str['features'].str[0].str['geometry'].str['coordinates'].str[::-1]

Two notes: - The above is basically equivalent to doing json.loads(row['value'])['features'][0]['geometry']['coordinates'][::-1] for each row - [::-1] reverse a list两个注意事项: - 以上基本上等同于为每一行执行json.loads(row['value'])['features'][0]['geometry']['coordinates'][::-1] - [::-1]反转列表

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

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