python - 根据分隔符将数据帧列拆分为两列

标签 python pandas dataframe split delimiter

我正在预处理文本以进行分类,并像这样导入数据集:

dataset = pd.read_csv('lyrics.csv', delimiter = '\t', quoting = 2)

数据集在终端上打印:

                                 lyrics,classification
0    I should have known better with a girl like yo...
1    You can shake an apple off an apple tree\nShak...
2    It's been a hard day's night\nAnd I've been wo...
3    Michelle, ma belle\nThese are words that go to...

但是,当我使用 spyder 更仔细地检查变量 dataset 时,我发现我只有一列,而不是所需的两列。

enter image description here

考虑到歌词本身有逗号和“,”分隔符不起作用,

如何更正上面的数据框以便:

1) 一栏歌词

2) 一列用于分类

每行都有相应的数据?

最佳答案

如果您的歌词本身不包含逗号(很可能包含),那么您可以将 read_csvdelimiter=',' 结合使用。

但是,如果这不是一个选项,您可以使用 str.rsplit:

dataset.iloc[:, 0].str.rsplit(',', expand=True)
<小时/>
df

                               lyrics,classification
0  I should have known better with a girl like yo...
1                              You can shake an...,0
2                  It's been a hard day's night...,0

df = df.iloc[:, 0].str.rsplit(',', 1, expand=True)
df.columns = ['lyrics', 'classification']
df

                                              lyrics classification
0  I should have known better with a girl like yo...              0
1                                You can shake an...              0
2                    It's been a hard day's night...              0

关于python - 根据分隔符将数据帧列拆分为两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46165775/

相关文章:

python - Pandas - Groupby 或将多个数据帧剪切到垃圾箱

python - 使用自定义函数后如何存储新的数据框?

python - 将二维列表(tfidf 结果的密集输出)附加到 pandas 数据帧行中,每个索引

python - 从 group by 输出转换为 pandas 中的单独列

Python/Pandas Dataframe 将 0 替换为中值

python - 排序列表时嵌套的 lambda 语句

python - 如何将图形(3x3 子图)插入 matplotlib python 的子图中

python - 使用 python 读取大型 xlsx 文件的一部分

python:仅覆盖抽象类中的一些方法

python - 从 Pandas 数据帧创建边缘列表