通过pandas中的每一行迭代python脚本

通过pandas中的每一行迭代python脚本,python,python-3.x,pandas,dataframe,automation,Python,Python 3.x,Pandas,Dataframe,Automation,我有一个通过slack发送twitter警报的python脚本:- def twitter_setup(): """ Utility function to setup the Twitter's API with our access keys provided. """ # Authentication and access using keys: auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUME

我有一个通过slack发送twitter警报的python脚本:-

def twitter_setup():
    """
    Utility function to setup the Twitter's API
    with our access keys provided.
    """
    # Authentication and access using keys:
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)

    # Return API with authentication:
    api = tweepy.API(auth)
    return api


extractor = twitter_setup()
# We create a tweet list as follows:
tweets = extractor.user_timeline(screen_name="**FortniteGame**", count=200)


data = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets'])

# We add relevant data:
data['ID'] = np.array([tweet.id for tweet in tweets])
data['Date'] = np.array([tweet.created_at for tweet in tweets])
data['text'] = np.array([tweet.text for tweet in tweets])
#data['Date'] = pd.to_datetime(data['Date'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('US/Eastern')

created_time = datetime.datetime.utcnow() - datetime.timedelta(minutes=1)

data = data[(data['Date'] > created_time) & (
    data['Date'] < datetime.datetime.utcnow())]

my_list = ['Maintenance', 'Scheduled', 'downtime', 'Issue', 'Voice', 'Happy',
           'Problem', 'Outage', 'Service', 'Interruption', 'voice-comms', 'Downtime']

ndata = data[data['Tweets'].str.contains(
    "|".join(my_list), regex=True)].reset_index(drop=True)


slack = Slacker('xoxb-3434-4334-fgsgsdfsf')

#message = "test message"
slack.chat.post_message('#ops-twitter-alerts', 'FNWP :' +' '+ ndata['Tweets'] + '<!channel|>')
我想对每个客户机使用相同的脚本,我想对其进行迭代,并假设首先对Fortnite、PUBG和abhi98358使用相同的脚本,并且以相同的方式一步一步地进行

样本df:

t = pd.DataFrame({'A': ['FortniteGame', 'PUBG', 'abhi98358']})
示例迭代:

for index, row in t.iterrows():
   print "**" + row['A'] +"**"
上面的示例输出:

**FortniteGame**
**PUBG**
**abhi98358**
对于您的代码:

for index,rows in df.iterows():
   tweets = extractor.user_timeline(screen_name=("**" + row['twittername'] +"**"), count=200)
你可以像下面这样做

twtLst = []
for _, row in df.iterrows():
   twtDtl = row['client'], row['domain'], row['twittername']
   twtLst.append(twtDtl)
for twt in twtLst:
    client, domain, twtname = twt
    tweets = extractor.user_timeline(screen_name="**" + twtname +"**", count=200)
    #message = "test message"
    slack.chat.post_message('#ops-twitter-alerts', domain + ':' + client +' '+ndata['Tweets'] + '<!channel|>')
twtLst将是一个元组列表,然后您可以像下面这样相应地访问它

twtLst = []
for _, row in df.iterrows():
   twtDtl = row['client'], row['domain'], row['twittername']
   twtLst.append(twtDtl)
for twt in twtLst:
    client, domain, twtname = twt
    tweets = extractor.user_timeline(screen_name="**" + twtname +"**", count=200)
    #message = "test message"
    slack.chat.post_message('#ops-twitter-alerts', domain + ':' + client +' '+ndata['Tweets'] + '<!channel|>')
对于twtLst中的行波管:
客户端,域,twtname=twt
tweets=extractor.user\u timeline(screen\u name=“**”+twtname+“**”,count=200)
#message=“测试消息”
slack.chat.post_消息(“#ops twitter alerts”,domain+”:“+client+”+ndata['Tweets']+”)
给你

参考我的解决方案

对于dff.iterrows()中的索引行:
twt=行['twittername']
域=行['domain']
打印(行波管)
打印(域)
提取器=twitter_setup()
#我们创建了一个tweet列表,如下所示:
tweets=extractor.user\u时间线(screen\u name=twt,count=200)
data=pd.DataFrame(data=[tweet.text用于tweets中的tweet],columns=['tweets'])
#我们添加了相关数据:
数据['ID']=np.array([tweet.ID用于tweets中的tweet])
数据['Date']=np.array([tweet.created_at for tweets in tweets])
数据['text']=np.array([tweet.text用于tweets中的tweet])
#数据['Date']=pd.to_datetime(数据['Date'],单位为ms')。dt.tz_本地化('UTC')。dt.tz_转换('US/Eastern'))
已创建\u time=datetime.datetime.utcnow()-datetime.timedelta(分钟=160)
data=data[(data['Date']>created_time)和(data['Date']0:
slack.chat.post_消息(“#ops twitter alerts”,domain+”:“+ndata['Tweets']+”)
其他:
打印('hi')

使用iterrows或for循环就足以遍历dataframehey@SarthakNegi我是python新手。。。我擅长编写脚本,但不擅长循环等等。这里有两个我想动态设置的变量,一个是twitter名称,另一个是'FNWP:'+客户端名称。如果您可以提供一些示例代码。@ak333的可能副本:我可以看到您仅在这行代码上使用列
twittername
tweets=extractor.user\u timeline(screen\u name=“**FortniteGame**”,count=200)
。因此,您只需要对其使用迭代,而不是硬编码
FortniteGame
?。如果我错了,请纠正我?在第二部分中,我只需要屏幕名称,其他什么都不需要,所以我应该执行soemthign,比如tweets=extractor.user\u timeline(screen\u name=“**”,count=200)。对吗?是的,对,
“**”+twtname+“**”
只是3个字符串的串联,同时为两个客户端提供推文列表。我希望它应该对每个客户端逐个执行相同的过程,而不是一起执行。我现在就要尝试确保非常感谢我正在尝试,如果我不能,我将再次发布,如果它解决了您的问题,请接受并向未来用户投票!!因此,它与您的示例一起工作,但当我尝试我的示例时,它说AttributeError:“DataFrame”对象没有属性“iterows”……而且我不希望同时获得所有用户的tweet,我希望它为一个用户完成脚本,然后进入第二行,依此类推,仍然是同一个问题…下面我为索引编写了t.iterows中的行:tweets=extractor.user_timeline(screen_name=(row.twittername),count=200)data=pd.DataFrame(data=[tweet.text for tweets in tweets],columns=['tweets'])我们添加了相关数据:data['ID'=np.array([tweet.ID for tweets in tweets in tweets])data['Date]=np.array([tweet.created_at for tweets in tweets])数据['text']=np.array([tweet.text for tweets in tweets])