gpt4 book ai didi

python - Pandas:从键:值对字符串重建数据帧

转载 作者:太空宇宙 更新时间:2023-11-03 17:00:08 25 4
gpt4 key购买 nike

假设我有以下数据集:

  0
0 foo:1 bar:2 baz:3
1 bar:4 baz:5
2 foo:6

因此,每一行本质上都是一个序列化为字符串的字典,其中键:值对由空格分隔。每行有数百个key:value对,而唯一键的数量有几千个。可以这么说,数据是稀疏的。

我想要得到的是一个很好的 DataFrame,其中键是列,值是单元格。缺失值将被零替换。像这样:

  foo bar baz
0 1 2 3
1 0 4 5
2 6 0 0

我知道我可以将字符串拆分为键:值对:

In: frame[0].str.split(' ')
Out:
0
0 [foo:1, bar:2, baz:3]
1 [bar:4, baz:5]
2 [foo:6]

但是接下来会发生什么?

编辑:我在 AzureML Studio 环境中运行。所以效率很重要。

最佳答案

您可以尝试列表理解,然后创建新的DataFrame from_recordsfillna0:

s = df['0'].str.split(' ')

d = [dict(w.split(':', 1) for w in x) for x in s]
print d
#[{'baz': '3', 'foo': '1', 'bar': '2'}, {'baz': '5', 'bar': '4'}, {'foo': '6'}]

print pd.DataFrame.from_records(d).fillna(0)
# bar baz foo
#0 2 3 1
#1 4 5 0
#2 0 0 6

编辑:

如果在函数from_records中使用参数indexcolumns,可以获得更好的性能:

print df
0
0 foo:1 bar:2 baz:3
1 bar:4 baz:5
2 foo:6
3 foo:1 bar:2 baz:3 bal:8 adi:5

s = df['0'].str.split(' ')
d = [dict(w.split(':', 1) for w in x) for x in s]
print d
[{'baz': '3', 'foo': '1', 'bar': '2'},
{'baz': '5', 'bar': '4'},
{'foo': '6'},
{'baz': '3', 'bal': '8', 'foo': '1', 'bar': '2', 'adi': '5'}]

如果最长的字典拥有所有键,这会创建所有可能的列:

cols = sorted(d, key=len, reverse=True)[0].keys()
print cols
['baz', 'bal', 'foo', 'bar', 'adi']

df = pd.DataFrame.from_records( d, index= df.index, columns=cols )
df = df.fillna(0)

print df
baz bal foo bar adi
0 3 0 1 2 0
1 5 0 0 4 0
2 0 0 6 0 0
3 3 8 1 2 5

EDIT2:如果最长的字典不包含所有键并且键位于其他字典中,请使用:

list(set( val for dic in d for val in dic.keys()))

示例:

print df
0
0 foo1:1 bar:2 baz1:3
1 bar:4 baz:5
2 foo:6
3 foo:1 bar:2 baz:3 bal:8 adi:5

s = df['0'].str.split(' ')
d = [dict(w.split(':', 1) for w in x) for x in s]

print d
[{'baz1': '3', 'bar': '2', 'foo1': '1'},
{'baz': '5', 'bar': '4'},
{'foo': '6'},
{'baz': '3', 'bal': '8', 'foo': '1', 'bar': '2', 'adi': '5'}]

cols = list(set( val for dic in d for val in dic.keys()))
print cols
['bar', 'baz', 'baz1', 'bal', 'foo', 'foo1', 'adi']

df = pd.DataFrame.from_records( d, index= df.index, columns=cols )
df = df.fillna(0)

print df
bar baz baz1 bal foo foo1 adi
0 2 0 3 0 0 1 0
1 4 5 0 0 0 0 0
2 0 0 0 0 6 0 0
3 2 3 0 8 1 0 5

关于python - Pandas:从键:值对字符串重建数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35065490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com