熊猫数据框遍历列的python代码

时间:2019-04-25 17:50:35

标签: python-3.x pandas

我有一个数据框,

enter image description here

如您所见,

有两列。一个拥有公司名称,另一个拥有与每个公司名称相对应的文本字符串。

我想在每个文本上执行这些代码行。 (以下代码中的句子应该是每个文本)

def nlp_func(text)
 neg = 0
 pos = 0
 sentence = sentence.lower()
 for word in words:
    classResult = classifier.classify( word_feats(word))
    if classResult == 'neg':
        neg = neg + 1
    if classResult == 'pos':
        pos = pos + 1
 if (pos>neg)
  print('Positive: ' + str(float(pos)/len(words)))
 else
 print('Negative: ' + str(float(neg)/len(words)))

我不想将结果打印出来,而是将其存储在另一个看起来像这样的数据框中

company_names     value
3M Company         pos
ANSYS              neg

我是python和pandas的新手,所以我不知道该怎么做。我需要在两个地方提供帮助。

首先:如何将与company_names对应的文本作为参数发送给函数nlp_func?

第二:如何在每次调用函数时创建另一个数据框并存储值?

1 个答案:

答案 0 :(得分:0)

让您的数据框类似:

import pandas as pd

df = pd.DataFrame({"Company":["A", "B"],
                   "Sentence":["Something here", "Something there"]})

即:

    Company Sentence
0      A    something here
1      B    something there

那么您的功能应该是:

def nlp_func(df):
    res = {}
    for r in df.itertuples():
        # DO YOUR NLP ANALYSIS
        # code
        # code
        # code
        if (pos>neg):
            res[r.Company] = "Pos"
        else:
            res[r.Company] = "Neg"
    return pd.DataFrame(res.items(), columns=["Company", "Value"])

请注意:

  1. 您通过for r in df.itertuples():遍历数据框中的行
  2. 您在Company的{​​{1}}列中获得了值
  3. 您在r.Company的{​​{1}}列中获得了值
相关问题