【发布时间】:2021-01-02 03:27:12
【问题描述】:
我正在编写一个程序,它从 CSV 文件中读取 comment.ids 系列,将新的 comment.id 附加到系列,然后将新系列保存为 CSV。
这是我所拥有的:
def get_cache(path_=PATH_CACHE):
""""
If cache does not exist, it creates one. Otherwise, it loads the
cache into memory.
"""
print('Searching for cache...')
if os.path.exists(path_)==True:
print('Cache exists')
cache = pd.read_csv(path_)
print('Cache loaded')
else:
print('Cache does not exist')
cache = pd.Series(['test1', 'test2'], name='commentid', dtype=str)
print('Cache created')
return cache
def run(reddit, reply, cache, sub='test'):
"""
Posts on the specified subreddit if a comment containing a keyword
is found. Updates cache in memory.
"""
subreddit = reddit.subreddit(sub)
comments = subreddit.comments(limit=25)
print('Searching for comments...')
for comment in comments:
comment_text = comment.body
isMatch = any(string in comment_text for string in MATCH_WORDS)
if isMatch and comment.id not in cache.values:
print('Comment found!')
# comment.reply(reply)
print('Replied!')
cache = cache.append(pd.Series([comment.id], dtype=str),
ignore_index=True)
print('{} added to cache'.format(comment.id))
else:
print('Skip')
print('Done Searching \nCache:\n {}'.format(cache))
return cache
def update_cache(cache, path_=PATH_CACHE):
"""
Saves cache as csv to same path as it was loaded in from, replacing
the csv file.
"""
cache.to_csv(path_, index=False)
print('Cache saved as csv')
当找到新的comment.id 时,我得到cache 的以下内容:
其中gshiiiq 是在调用run() 时找到的comment.id。我希望将gshiiiq 附加到现有列的末尾,而不添加新列。
任何帮助将不胜感激。
【问题讨论】:
-
是
cache一个 pd.Series,您要传递给 run() 函数吗? -
也许你应该使用列表而不是 pd.Series;并在程序的最后将其转换为 pd.Series,即尽可能晚地进行转换。
-
问题可能是因为您试图将
pd.Series附加到pd.DataFrame-pd.read_csv不会返回具有默认选项的系列 -
@AsishM。是的!谢谢你。我没有意识到
pd.read_csv()返回一个数据框。我设置了squeeze=True,它现在可以工作了。
标签: python-3.x pandas series