使用pandas打印csv时从字符串数组中删除括号

2024-03-28 08:08:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个.csv文件。其中一列是“单词”。每一类单词都在一行中,单元格“words”有一个单词列表,我将其读作:

words = []

for i in range(len(category)):

    r = requests.post(base_url+'/'+url[i])

    if r.ok:
        data = r.content.decode('utf8')
        words.append(pd.Series.tolist((pd.read_csv(io.StringIO(data), squeeze=True)).T))

url_f = [base_url + s  for s in url]


df = pd.DataFrame({'category': category, 'url': url_f, 
                   'words': words})

df.to_csv("lm_words.csv")

单词列表以r形式下载

桌子看起来像这样:

^{pr2}$

我正试图去掉[单词1,word2,word3]中的括号。

我用R写的,它不打印.csv中的括号

编辑1:格式


Tags: 文件csvinurldf列表fordata
2条回答

如果您想去掉方括号,那么首先需要使用

    new_string = str(list_name)

之后,您可以在python中使用切片技术删除方括号:

^{pr2}$

使用str.join

例如:

df = pd.DataFrame({'category': category, 'url': url_f, 
                   'words': words})
df["words"] = df["words"].apply(", ".join)

相关问题 更多 >