【问题标题】:Explode a cell populated with multiple values into unique rows将填充有多个值的单元格分解为唯一行
【发布时间】:2020-06-01 15:58:02
【问题描述】:

我想将每个包含多个单词的单元格“分解”成不同的行,同时在连接时保留它的评级和 sysnet 值。我试图导入某人的 pandas_explode 库,但 VS 代码只是不想识别它。在 pandas 文档或一些漂亮的 for 循环中是否有任何方法可以提取和重新分配这些单词?示例 csv 在 img 链接中

import json
import pandas as pd # version 1.01

df = pd.read_json('result.json')
df.to_csv('jsonToCSV.csv', index=False) 
df = pd.read_csv('jsonToCSV.csv') 


df = df.explode('words')

print(df)

df = df.to_csv(r'C:\Users\alant\Desktop\test.csv', index = None, header=True)

上面运行时的输出:

   synset  rating                                              words
0     1034312     0.0             ['discourse', 'talk about', 'discuss']
1      146856     0.0          ['merging', 'meeting', 'coming together']
2      829378     0.0     ['care', 'charge', 'tutelage', 'guardianship']
3     8164585     0.0  ['administration', 'governance', 'governing bo...
4     1204318     0.0               ['nonhierarchical', 'nonhierarchic']
...       ...     ...                                                ...
8605  7324673     1.0               ['emergence', 'outgrowth', 'growth']

csv file

【问题讨论】:

  • 你用的是什么版本的熊猫?最新内置explode()功能
  • 我在我的wsl上的vs代码上使用python 3.7.3上的1.01版
  • 你尝试过使用df.explode()函数吗?
  • synset 评分词 0 1034312 0.0 ['discourse', 'talk about', 'discuss'] 1 146856 0.0 ['merging', 'meeting', 'coming together'] 2 829378 0.0 [' care', 'charge', 'tutelage', 'guardianship'] ...这是我在运行 df.explode('words') 时得到的结果,所以我假设爆炸列不起作用。我必须以某种方式指示一个单元格吗?
  • 请将您的示例输入和输出作为文本包含在您的问题中,而不是图像或 cmets,以创建 minimal reproducible example

标签: python json pandas csv explode


【解决方案1】:

如果您有需要防止爆炸的列,我建议先将它们设置为索引,然后再爆炸。

对于你的例子,试试这是否适合你。

df = df.set_index(['synset','rating']).apply(pd.Series.explode) # this would work for exploding multiple columns as well

# then reset the index

df = df.reset_index()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    相关资源
    最近更新 更多