我试图对Series对象“tweet_text”中的每个字符串进行更改,但由于某些原因,当我在for循环中对tweets进行更改后打印Series对象时,得到的字符串与for循环之前相同。我该怎么解决这个问题?在
import pandas as pd
import re
import string
df = pd.read_csv('sample-tweets.csv',
names=['Tweet_Date', 'User_ID', 'Tweet_Text', 'Favorites', 'Retweets', 'Tweet_ID'])
sum_df = df[['User_ID', 'Tweet_ID', 'Tweet_Text']].copy()
sum_df.set_index(['User_ID'])
# print sum_df
tweet_text = df.ix[:, 2]
print type(tweet_text)
# efficiency could be im proved by using translate method
# regex = re.compile('[%s]' % re.escape(string.punctuation))
for tweet in tweet_text:
tweet = re.sub('https://t.co/[a-zA-Z0-9]*', "", tweet)
tweet = re.sub('@[a-zA-Z0-9]*', '', tweet)
tweet = re.sub('#[a-zA-Z0-9]*', '', tweet)
tweet = re.sub('$[a-zA-Z0-9]*', '', tweet)
tweet = ''.join(i for i in tweet if not i.isdigit())
tweet = tweet.replace('"', '')
tweet = re.sub(r'[\(\[].*?[\)\]]', '', tweet) # takes out everything between parentheses also, fix this
# gets rid of all punctuation and emoji's
tweet = "".join(l for l in tweet if l not in string.punctuation)
tweet = re.sub(r'[^\x00-\x7F]+',' ', tweet)
# gets ride of all extra spacing
tweet = tweet.lower()
tweet = tweet.strip()
tweet = " ".join(tweet.split())
count = count + 1
# print tweet
print tweet_text
发生这种情况的原因是
tweet_text
对于初学者来说是列df.ix[:, 2]
的副本。第二,这不是pandas迭代Series
的方式——应该使用apply()
。在要更新代码,将进入循环的所有内容都转换为函数:
然后,代替:
^{pr2}$执行:
顺便说一句,不要使用
ix
索引器,因为它已经贬值,并将在熊猫的未来版本中删除。在Python字符串是不可变的。您只是更改了变量
tweet
的属性值,但从未实际更新dataframe。在您只需将更新后的值重新插入数据帧。简单修复示例:
相关问题 更多 >
编程相关推荐