使用熊猫打印为CSV时从字符串数组中删除括号

时间:2019-05-13 10:00:33

标签: python pandas csv

我想编写一个.csv文件。列之一是“单词”。每个类别的单词都排成一行,“单词”单元格中有一个单词列表,我读为:

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。

表看起来像这样:

index | category | url | words
0.    | cat1.    | www.| [word1, word2, word3]

我想摆脱 [ word1,word2,word3 ] 中的括号。

我用R编写了此代码,它没有在.csv中打印括号

Edit1:格式

2 个答案:

答案 0 :(得分:0)

使用str.join

例如:

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

答案 1 :(得分:0)

如果要删除方括号,则首先需要使用

将列表转换为字符串
>>> import pandas as pd 
>>> def groupby_index(df):
    return pd.DataFrame(data = {'key':[1,1,1,2,2,3,3,4],'group_idx':[0,1,2,0,1,0,1,0]})
>>> df = pd.DataFrame(data = {'key':[1,1,1,2,2,3,3,4]})
>>> groupby_index(df)
   key  group_idx
0    1          0
1    1          1
2    1          2
3    2          0
4    2          1
5    3          0
6    3          1
7    4          0   

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

df.groupby('key').cumcount().reset_index()