我使用twitter ID填充数据框中的某些行。我第一次运行脚本而没有除了,我遇到了错误:
[{'code': 144, 'message': 'No status found with that ID.'}]
我理解这可能是因为有人删除了推文或其他原因。但是,我需要坚持下去!
所以我使用了except: pass
,但它实际上并没有返回任何内容。所有行都是空的。我一直在努力工作,但我不知道要解决它。
我的数据框:
TweetID text pageType
index
id1 My code is not working http://blablabla.com
id2 451864165416 Nan twitter
id3 849849849844 Nan twitter
以下代码不会返回任何内容:
try:
if (df['pageType'] == 'twitter').any:
df['text'] = df.tweetID.apply(lambda x: api.get_status(x).text)
except:
pass
那就是它! 非常感谢!
答案 0 :(得分:1)
我建议使用布尔索引 + loc
+ apply
:
mask = df['pageType'] == 'twitter'
df.loc[mask, 'text'] = df.loc[mask, 'twitterID']\
.apply(lambda x: api.get_status(x).text)
答案 1 :(得分:0)
问题是,您的try
和except
设置会在apply
完成之前停止执行,而for-loop
永远不会创建新列。通常,您会将此子句放在tweetID
中,就像您使用它一样。相反,您可以创建自定义函数,以便捕获无效的def GetStuff(value):
try:
return api.get_status(value).text
except:
return "ERROR"
df['text'] = df.tweetID.apply(lambda x: GetStuff(x))
值的错误。
def GetStuff(value):
try:
return api.get_status(value).text
except:
return "ERROR"
df['text'] = df.where(df.tweetID == 'twitter').tweetID.apply(lambda x: GetStuff(x))
满足评论中的条件:
选项1
tweetID
适用于twitter
== NaN
的函数,其他值为fillna()
,您可以使用GetStuff()
替换其他文字
选项2
在def GetStuff(value):
if value == 'twitter':
try:
return api.get_status(value).text
except:
return "ERROR"
else:
return 'NotTwitter'
df['text'] = df.tweetID.apply(lambda x: GetStuff(x))
函数中构建条件。
{{1}}