列表对多标签计数器的理解

时间:2017-10-18 15:36:14

标签: python pandas numpy

我已经制作了以下代码,并且它的工作正常,但是我正在努力为此制作更具可读性和优化的代码我将替换我的代码以列出理解来替换所有"如果条件"寻找emotion_class(双**)。

尝试将**代码优化为列表理解:

emotion_classes = ["Joy", "Fear", "Anger", "Surprise","Sadness", "Trust","Anticipation"]

[increaseCounterofJoy,increaseCounterofFear, for emotion in emotion_classes]

代码

for idx in range(len(df_split)):

    iter_df = df_split[idx]

    i = 0

    final_df = pd.DataFrame(columns=("Date","Joy", "Fear", "Anger", "Surprise","Sadness", "Trust","Anticipation"))

    for index, row in iter_df.iterrows():

        **if iter_df["Emotion Class"] = "Joy":
            row["Joy"] = +1
        if iter_df["Emotion Class"] = "Fear":
            row["Fear"] = +1  
        if iter_df["Emotion Class"] = "Anger":
            row["Anger"] = +1
        if iter_df["Emotion Class"] = "Surprise":
            row["Surprise"] = +1
        if iter_df["Emotion Class"] = "Sadness":
            row["Sadness"] = +1
        if iter_df["Emotion Class"] = "Trust":
            row["Trust"] = +1
        if iter_df["Emotion Class"] = "Anticipation":
            row["Anticipation"] = +1**

        final_df.loc[i] = row["Date"], row["Joy"], row["Fear"], row["Anger"], row["Surprise"], row["Sadness"], row["Trust"], row["Anticipation"]

    i = i + 1

3 个答案:

答案 0 :(得分:2)

这不是列表理解有用的任务。只需使用传统的for循环:

emotion_classes = [
    "Joy", "Fear", "Anger", "Surprise",
    "Sadness", "Trust","Anticipation",
]

for index, row in iter_df.iterrows():
    for emotion in emotion_classes:
        if iter_df["Emotion Class"] == emotion:
            row[emotion] += 1

您的代码中存在一些拼写错误。您的测试中有=而不是==。我假设你想增加row中的相应字段,而不是仅将它们设置为+1

答案 1 :(得分:1)

PM 2Ring的答案有效,但我想知道您是否可以将其简化为:

for index, row in iter_df.iterrows():    
    row[iter_df["Emotion Class"]] += 1

答案 2 :(得分:0)

也许是数据透视表?

In [1]: iter_df
Out[1]:
   Date Emotion Class
0     1           Joy
1     1         Peace
2     2           Joy
3     3         Peace
4     3         Peace

In [2]: iter_df['ones'] = 1

In [3]: pd.pivot_table(iter_df, index='Date', columns='Emotion Class', values='ones', margins=False, aggfunc='sum')
    ...:
Out[3]:
Emotion Class  Joy  Peace
Date
1              1.0    1.0
2              1.0    NaN
3              NaN    2.0