[英]Python - Function for parsing key-value pairs into DataFrame columns
[英]Parsing key-value pairs into DataFrame columns
我有一个在pandas系列中按行嵌套的键值对。 什么是将它们分成单个列的最有效/最优化的方法? (我可以解压缩并进行转换,但最好的方法是什么?)
我不知道:
行是unicode字符串的列表。 一旦提取,值将始终是bigint。
输入:
parsedSeries.head()
0 [key1=774, key2=238]
1 [key1=524, key2=101, key3=848]
2 [key3=843]
3 [key1=232, key3=298, key2=457]
预期产量:
record key1 key2 key3
0 774 238 NAN
1 524 101 848
2 NAN NAN 843
3 232 457 298
请注意,输入由包含格式为u"X=Y"
Unicode字符串的列表组成,其中假定X
遵循用作Python中属性名称的任何必需约定,并且Y
始终可以解释为整数。 例如,以下内容可用于构建上述示例数据:
pandas.Series([[u"key1=774", u"key2=238"],
[u"key1=524", u"key2=101", u"key3=848"],
[u"key3=843"],
[u"key1=232", u"key3=298", u"key2=457"]])
“最佳”解决方案可能不会首先发现自己处于这种情况。 大多数情况下,当你在Series或DataFrame中有非标量数量时,你已经向错误的方向迈出了一步,因为你无法真正应用向量操作。
无论如何,从你的系列开始,你可以这样做:
>>> ds = [dict(w.split('=', 1) for w in x) for x in s]
>>> pd.DataFrame.from_records(ds)
key1 key2 key3
0 774 238 NaN
1 524 101 848
2 NaN NaN 843
3 232 457 298
好的,你的最终答案可能因你的例子有多精确而有所不同。 具体而言,可以调整解析数据的正则表达式。
让我们做一些imoprts并设置你的数据文件:
import re
import pandas as pd
from StringIO import StringIO
f = StringIO("""0 [key1=774, key2=238]
1 [key1=524, key2=101, key3=848]
2 [key3=843]
3 [key1=232, key3=298, key2=457]""")
现在我们准备开始了。 首先只是一些正则表达式魔法来获取行的dict表示:
# get the dicts
rows = [dict(re.findall('(key[0-9]*)=([0-9]*)',l)) for l in f]
# convert values to ints
rows = [dict((k,int(v)) for k,v in row.items()) for row in rows]
rows
输出:
[{'key1': 774, 'key2': 238},
{'key1': 524, 'key2': 101, 'key3': 848},
{'key3': 843},
{'key1': 232, 'key2': 457, 'key3': 298}]
那只是正则表达式,但你只是在那里:
pd.DataFrame(rows)
输出:
key1 key2 key3
0 774 238 NaN
1 524 101 848
2 NaN NaN 843
3 232 457 298
如果您愿意,可以转换为单行,但我将其分为两步,以便您可以调整正则表达式以适合您的实际数据文件。
为了将值作为整数而不是字符串处理,DSM使用from_records
进行了非常轻微的调整。
def key_to_int(split_vals):
return (split_vals[0], int(split_vals[1]))
def dictify(row):
return dict(key_to_int(elem.split("=")) for elem in row)
pandas.DataFrame.from_records(parsedSeries.map(dictify))
给
Out[518]:
key1 key2 key3
0 774 238 NaN
1 524 101 848
2 NaN NaN 843
3 232 457 298
[4 rows x 3 columns]
其中值为整数(由于NaN
值而且NumPy继续不支持整数NaN值,因此列仍为float
类型)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.