【问题标题】:Splitting a string in dataframe在数据框中拆分字符串
【发布时间】:2021-02-27 01:14:49
【问题描述】:

我有一个这样的数据框:

col1|col2
{"test":"23","test1":"12"}|1992
{"test":"24","test1":"19","test3":"24"}|1993
{"test":"27","test1":"20","test3":"21","test4":"40"}|1994

我想要这样的数据框:

col1_a|col1_b|col2
test|23|1992
test1|12|1992
test|24|1993
test1|19|1993
.
.
.
.
.
.

我怎样才能实现这个解决方案? 虽然数据是字典类型,但在dataframe中以字符串形式存储

【问题讨论】:

  • 这些数据看起来根本不像数据框
  • @Marat 其实是dataframe中的字典
  • @Sam 请试试我的回答。

标签: python python-3.x pandas python-2.7 dataframe


【解决方案1】:

df 为例:

In [2063]: df = pd.DataFrame({'col1':[{"test":"23","test1":"12"}, {"test":"24","test1":"19","test3":"24"}, {"test":"27","test1":"20","test3":"21","test4":"40"}], 'col2':[1992, 1993, 1994]})

In [2064]: df
Out[2064]: 
                                                col1  col2
0                      {'test': '23', 'test1': '12'}  1992
1       {'test': '24', 'test1': '19', 'test3': '24'}  1993
2  {'test': '27', 'test1': '20', 'test3': '21', '...  1994

您可以将df.applydf.explode() 一起使用:

In [2085]: df.col1 = df.col1.apply(lambda x: list(x.items()))

In [2086]: df = df.explode('col1')

In [2091]: df[['col1_a', 'col1_b']] = pd.DataFrame(df.col1.tolist(), index=df.index)

In [2093]: df = df[['col1_a', 'col1_b', 'col2']]

In [2094]: df
Out[2094]: 
  col1_a col1_b  col2
0   test     23  1992
0  test1     12  1992
1   test     24  1993
1  test1     19  1993
1  test3     24  1993
2   test     27  1994
2  test1     20  1994
2  test3     21  1994
2  test4     40  1994

【讨论】:

  • 实际上列的数据类型是字符串,因此这可能不适用。有没有办法将值转换为字典然后应用它?
  • 因此,当我尝试您的解决方案时,我收到如下错误:'str' object has no attribute 'items' @Mayank
  • 通过更改数据类型和您的解决方案解决了它
【解决方案2】:

将字典值扩展到列,然后熔化/向下旋转表格。

df = pd.DataFrame([[{"test":"23","test1":"12"},1992],
[{"test":"24","test1":"19","test3":"24"},1993],
[{"test":"27","test1":"20","test3":"21","test4":"40"},1994]],columns=['c1','c2'])

pd.DataFrame(df['c1'].values.tolist(), index=df.c2) \
    .reset_index() \
    .melt(id_vars='c2',var_name='col1_a',value_name='col1_b') \
    .dropna()

输出:

    c2  col1_a  col1_b
0   1992    test    23
1   1993    test    24
2   1994    test    27
3   1992    test1   12
4   1993    test1   19
5   1994    test1   20
7   1993    test3   24
8   1994    test3   21
11  1994    test4   40

【讨论】:

  • 其实字典是作为字符串存储的,还有很多值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 2015-06-25
  • 2022-11-20
  • 1970-01-01
相关资源
最近更新 更多