【问题标题】:reducing a column of CSV lists to a single list将一列 CSV 列表缩减为单个列表
【发布时间】:2019-04-29 13:07:59
【问题描述】:

我正在使用 Python3 从 Excel 电子表格中读取一列:

import pandas as pd
from pandas import ExcelFile
df = pd.read_excel('MWE.xlsx', sheet_name='Sheet1')
print(df)

                   col1                        col2
0         starts normal                  egg, bacon
1  still none the wiser         egg, sausage, bacon
2      maybe odd tastes                   egg, spam
3     or maybe post-war            egg, bacon, spam
4  maybe for the hungry   egg, bacon, sausage, spam
5                 bingo  spam, bacon, sausage, spam

我想将 col2 减少为 col2 中单词的单个列表(例如 egg、bacon、...)。

df.col2.ravel() 似乎将col2 简化为字符串列表。

df.col2.flatten() 产量

AttributeError: 'Series' object has no attribute 'flatten' 

【问题讨论】:

    标签: python pandas flatten


    【解决方案1】:

    如果您想要将一系列列表作为 col2,这可以解决问题:

    df = pd.DataFrame({'col1': ['starts normal','still none the wiser'], 'col2': ['egg, bacon','egg, sausage, bacon']})
    
    df['col2'] = df['col2'].map(lambda x: [i.strip() for i in x.split(',')])
    print(df)
    

    结果:

                       col1                   col2
    0         starts normal           [egg, bacon]
    1  still none the wiser  [egg, sausage, bacon]
    

    【讨论】:

    • 谢谢。我已经编辑了我的描述以澄清我正在寻找一个单词列表作为我的输出,例如[鸡蛋、培根、鸡蛋、香肠、培根……]。如何将代码生成的输出扁平化为单个单词列表?
    【解决方案2】:

    也许这就是你需要的:

    1. 将一系列逗号分隔的字符串转换为列表列表

      arrs = df.col2.map(lambda x: [i.strip() for i in x.split(',')]).tolist()
      # [['egg', 'bacon'], ['egg', 'sausage', 'bacon'], ...]
      
    2. 获取包含唯一项目的列表

      unique = list({elem for arr in arrs for elem in arr})
      # ['spam', 'sausage', 'egg', 'bacon']
      

    【讨论】:

    • 漂亮 - 谢谢:完全正确,并且更进一步预测了我接下来想做什么。
    【解决方案3】:

    尝试一些简单的方法,例如:

    df = pd.DataFrame({'col2': [list('abc'), list('de'), list('fghi')]})
    flat_col2 = [element for row in df.col2 for element in row]
    # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
    

    【讨论】:

    • 谢谢。这给了我一个单独的字符列表:我编辑了我的描述以澄清我想要一个单词列表。你知道是否有一种简单的方法可以改变迭代以对单词而不是字符进行迭代?
    猜你喜欢
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 2020-07-19
    • 2018-12-03
    • 2013-07-10
    • 2019-10-01
    • 1970-01-01
    • 2016-05-27
    相关资源
    最近更新 更多