【发布时间】:2020-05-31 08:01:02
【问题描述】:
我有一个类似于以下的数据集。
date,score
3/1/16,0.6369
5/1/16,-0.2023
6/1/16,0.04
7/1/16,0.0772
9/1/16,-0.4215
12/1/16,0.2960
15/1/16,0.25
15/1/16,0.7684
我想在乐谱上应用以下条件。
Con1: if the score is >.05, count that as positive for that date
Con2: if the score is -0.05<=score <=.05, count that as neutral for that date
Con3: Else, count that as negative for that date
And add a new_column to the DataFrame alongside the score to put the 'negative'/'positive'/'neutral' result
预期输出:
date, score, mood
3/1/16,0.6369, positive
5/1/16,-.2023, negative
6/1/16,0.04, neutral
我在同一日期有多个分数。所以,我想到了使用多列('date'和'score')的groupby,并通过if条件并向DataFrame添加一个新列['mood']。
我尝试过的:
df =pd.read_csv('file.csv')
def SortMood(df)
df['mood']=[] #empty column as a list in the df to store the mood
for score in df['score']:
if score>(0.05):
df['mood'].append('positive')
elif -0.05<=score <=.05:
df['mood'].append('neutral')
else:
df['mood'].append('negative')
我知道这个函数是错误的(我得到一个 ValueError)。因此,任何帮助表示赞赏。谢谢。
【问题讨论】:
-
当同一日期的不同分数给出不同答案时,您的预期输出是什么?
-
@andrew_reece 它是根据 if/else 语句。实际上,同一天我有很多不同的分数。谢谢
-
@Non_linear 尚不清楚 if/else 语句在同一日期有多个评估的情况下应如何应用。您是否期望每个日期只有一个输出?如果是这样,那将需要
groupby。如果您可以 (a) 指定完整的预期输出并且 (b) 在同一日期包含具有两个不同结果的边缘情况,那将会很有帮助。 (目前 15/1/16 有两个条目,但它们都评估为正面。) -
@andrew_reece 我应该说的。但是,您建议的解决方案也可以解决此问题。我刚刚检查了一个日期的输出结果,其中有 3 个不同的案例(正面、负面和中性)得分不同,它似乎对所有这些案例都进行了正确分类。谢谢。