【问题标题】:Converting or formating nested list with name of month into new list in python将具有月份名称的嵌套列表转换或格式化为python中的新列表
【发布时间】:2021-03-07 01:01:26
【问题描述】:

我有一个这样的嵌套列表:

data = [[[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [['tiktok', 'tenaga kesehatan'], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [['kanker'], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [['jantung'], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [['jantung'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19', 'covid-19'], 'October'],
 [['covid-19'], 'October'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [[], 'September'],
 [['covid-19', 'covid-19'], 'September'],
 [['jantung'], 'September'],
 [['jantung'], 'September'],
 [['covid-19'], 'September'],
 [['covid-19'], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [[], 'August'],
 [[], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [['jantung'], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [['covid-19', 'covid-19'], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'July']]

我想按月份的名称计算所有令牌 ('covid-19','jantung'... etc),这样我就可以按月获取令牌频率。

这是我的预期输出:

result = [
    ['covid-19',0,0,0,0,0,0,1,19,17,21,0,0],
    ['tiktok',0,0,0,0,0,0,0,0,0,1,0,0],
    ['jantung',0,0,0,0,0,0,0,1,2,2,0,0],
    ['kanker',0,0,0,0,0,0,0,0,0,1,0,0],
    ['tenaga kesehatan',0,0,0,0,0,0,0,0,0,1,0,0],   
]

请注意:'0,0,0,0,0,0,1,19,17,21,0,0'1 月到 12 月的顺序该月令牌的总和。请建议我一种将嵌套转换为的方法结果列表。

有什么想法吗?

【问题讨论】:

  • 您好!你尝试了什么?

标签: python list dataframe nested


【解决方案1】:

我建议您将嵌套列表更改为这样的字典

{
  "October":{
     "covid-19":8,
     "jantung":5
  },
  "November":{...},
  ...
}

或者像这样

{
  "covid-19":{
     "Oktober":8,
     "November":5
  },
  "Jantung":{...},
  ...
}

【讨论】:

  • 谢谢,也许你说的用字典比较好
【解决方案2】:

你真的不应该在这样的列表中存储不同的数据,看起来像这样的东西怎么样?

{'covid-19': [0, 0, 0, 0, 0, 0, 0, 1, 17, 15, 19, 0],
 'jantung': [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 0],
 'kanker': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
 'tenaga kesehatan': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
 'tiktok': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]}

这里有一个代码 sn-p 来制作这个字典:

from collections import defaultdict
result = defaultdict(lambda: [0]*12)
for i in data: 
    if i[0]: 
        for j in i[0]: 
            result[j][datetime.datetime.strptime(i[1],"%B").month - 1] += 1

【讨论】:

  • 用字典完美解决!,但是令牌(covid-19,tiktok,e.t.c....)是如何在11月存在的?其中数据仅为 7 月、8 月、9 月和 10 月
  • 抱歉 datetime 对象的月份不是 0 索引(1 是 1 月)通过从月份中减去 1 来修复(现在意味着 1 月份的索引为 0)
【解决方案3】:

这里我们提出了一个可能的解决方案:

import calendar

data = [[[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [['tiktok', 'tenaga kesehatan'], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [['kanker'], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [['jantung'], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [[], 'October'],
 [['covid-19'], 'October'],
 [[], 'October'],
 [['jantung'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19'], 'October'],
 [['covid-19', 'covid-19'], 'October'],
 [['covid-19'], 'October'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [[], 'September'],
 [['covid-19', 'covid-19'], 'September'],
 [['jantung'], 'September'],
 [['jantung'], 'September'],
 [['covid-19'], 'September'],
 [['covid-19'], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [[], 'September'],
 [['covid-19'], 'September'],
 [[], 'September'],
 [[], 'August'],
 [[], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [['jantung'], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'August'],
 [[], 'August'],
 [['covid-19'], 'August'],
 [['covid-19', 'covid-19'], 'August'],
 [['covid-19'], 'August'],
 [['covid-19'], 'July']]

final = []
for el in data:
    if len(el[0]) > 0:
        for key in el[0]:
            if key not in [sub[0] for sub in final]:
                final.append([key] + [0]*12)
            for sub in final:
                if sub[0] == key:
                    sub[list(calendar.month_abbr).index(el[-1][:3])] += 1

print(final)

输出将是:

[['covid-19', 0, 0, 0, 0, 0, 0, 1, 17, 15, 19, 0, 0], ['tiktok', 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], ['tenaga kesehatan', 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], ['kanker', 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], ['jantung', 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 0, 0]]

注意:然而,正如有人提到的,使用不同的数据结构来存储结果可能是个好主意。当然,字典会更方便,并且可以让您编写更线性的解决方案。

【讨论】:

  • 完美!但是令牌(covid-19,tiktok,e.t.c....)是如何在 11 月存在的?其中数据仅为 7 月、8 月、9 月和 10 月。
  • @AlMuhtadi 你是对的。我已经更新了解决问题的答案。这只是不必要的+ 1
【解决方案4】:

虽然其他人已经写出了非常好的答案,但我觉得通过 pandas 解决这个问题既更易于维护,也更冗长。此外,熊猫对象真的很容易使用。

首先导入:

import pandas as pd
import calendar
from pprint import pprint

代码主体如下:

df = pd.DataFrame(data, columns=["lists", "month"])
names = list(set([y for x in df["lists"] for y in x]))
df[names] = 0


def func(row):
    for n in names:
        for k in row["lists"]:
            if k == n:
                row[n] += 1
    return row


df = df.apply(func, axis=1)
df.drop(["lists"], inplace=True, axis=1)

new_df = df.groupby(by="month").sum().T.reset_index()
new_df.columns.name = None # Just for my taste to remove the "month" label of groupby result

months = list(calendar.month_name)[1:]  # list of months. There's an empty string at index 0.
new_df[[m for m in months if m not in new_df.columns]] = 0 #Creating columns for unseen months
new_df = new_df[["index"] + months] #sorting the months
print(new_df) 
pprint(new_df.values.tolist())

输出将是:

              index  January  February  ...  October  November  December
0            kanker        0         0  ...        1         0         0
1          covid-19        0         0  ...       19         0         0
2           jantung        0         0  ...        2         0         0
3            tiktok        0         0  ...        1         0         0
4  tenaga kesehatan        0         0  ...        1         0         0

[5 rows x 13 columns]


[['kanker', 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
 ['covid-19', 0, 0, 0, 0, 0, 0, 1, 17, 15, 19, 0, 0],
 ['jantung', 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 0, 0],
 ['tiktok', 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
 ['tenaga kesehatan', 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]

输出将是:

              index  January  February  ...  October  November  December
0  tenaga kesehatan        0         0  ...        1         0         0
1          covid-19        0         0  ...       19         0         0
2            kanker        0         0  ...        1         0         0
3           jantung        0         0  ...        2         0         0
4            tiktok        0         0  ...        1         0         0

[5 rows x 13 columns]


[['tenaga kesehatan', 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
 ['covid-19', 0, 0, 0, 0, 0, 0, 1, 17, 15, 19, 0, 0],
 ['kanker', 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
 ['jantung', 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 0, 0],
 ['tiktok', 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]


【讨论】:

  • 我也想和你一样,使用 pandas 并获取更易于维护的数据。我会考虑这样的!非常感谢!
【解决方案5】:

也许用函数式编程解决同样的问题。

from functional import seq 

NONE_KEY = 'NONE'
MONTHS = {
    'January': 1,
    'Feburary': 2,
    'March': 3,
    'April': 4,
    'May': 5,
    'June': 6,
    'July': 7,
    'August': 8,
    'September': 9,
    'October': 10,
    'November': 11,
    'December': 12
}

def reGroupByFirstItem(d):
    if (len(d[0]) > 0):
        return seq(d[0]).map(lambda key: (key, d[1])).to_list()
    else:
        return [(NONE_KEY, d[1])]

def hasKey(l, key):
    return seq(l).filter(lambda x: x[0] == key).len() > 0

def getIndexByKey(ll, key):
    for i in range(len(ll)):
        if ll[i][0] == key:
            return i    

def initList(key):
    l = [0 for x in range(12)]
    l.insert(0, key)
    return l 

def updateList(l, month):
    l[ MONTHS[month] ] += 1
    return l

def updateByKey(ll, key, val):
    i = getIndexByKey(ll, key)
    ll[i] = updateList(ll[i], val)
    return ll

def initListWithValue(key, val):
    l = initList(key)
    return updateList(l, val)

def createNewList(nextItem, current):
    key = nextItem[0]
    val = nextItem[1]
    
    if hasKey(current, key):
        current = updateByKey(current, key, val)
    else:
        current.append(initListWithValue(key, val))
    
    return current

result = seq(data)\
         .map(reGroupByFirstItem)\
         .flatten()\
         .fold_right([], createNewList)
         

print(result)


您确实需要先安装pyFunctional

pip install pyfunctional 

这里有完整的文档https://docs.pyfunctional.pedro.ai/en/latest/index.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 2011-09-30
    • 2021-10-11
    • 2012-02-12
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    相关资源
    最近更新 更多