简体   繁体   English

如何从多个分隔符值中将pandas中的csv文件读取为两列

[英]How to read csv file in pandas as two column from multiple delimiter values

I've a csv file like this:我有一个像这样的 csv 文件:

123, a, b, c, d
1433, b, c, d, e
2323, c, d, e, f
4543, d, e, f

I want to read this into dataframe but I want the first delimiter value as one column and rest as another column我想将其读入数据帧,但我希望第一个分隔符值作为一列,其余作为另一列

id         values
123        a, b, c, d
1433       b, c, d, e
2323       c, d, e, f
4543       d, e, f, NaN

I tried to use pandas read_csv but i couldn't find a option such as maxsplit there.我尝试使用pandas read_csv,但在那里找不到诸如maxsplit之类的选项。 If anyone is familiar with how to do it do help me out.如果有人熟悉如何做到这一点,请帮助我。

I put in a wrong delimiter in the read_csv function, which forces Pandas to read the data into one column, from there I split the column into the format I want.我在 read_csv 函数中输入了错误的分隔符,这会强制 Pandas 将数据读入一列,然后我将列拆分为我想要的格式。 Note however, this does not trump Datanovice's solution, as the NaN is not introduced:但是请注意,这并不能胜过 Datanovice 的解决方案,因为没有引入 NaN:

data = '''123, a, b, c, d
          1433, b, c, d, e
          2323, c, d, e, f
          4543, d, e, f'''

df = pd.read_csv(StringIO(data),sep=';', header= None, names=['string'])
df.string.str.split(pat=',', n=1,expand=True)

    0         1
0   123     a, b, c, d
1   1433    b, c, d, e
2   2323    c, d, e, f
3   4543    d, e, f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Pandas读取CSV并且只在没有Sep或Delimiter的情况下将其读入1列 - How to read a CSV with Pandas and only read it into 1 column without a Sep or Delimiter 如何读取 csv 文件,其中 pandas 在一列中有多个值? - How do I read a csv File with pandas that has multiple values in one column? 如何使用熊猫在最后一个字段中存在分隔符的情况下读取CSV文件? - How to use Pandas to read CSV file with delimiter existing in the last field? Pandas:是否可以使用多个符号分隔符读取 CSV? - Pandas: is it possible to read CSV with multiple symbols delimiter? 从文件读取的CSV分隔符 - CSV delimiter that is read from a file Pandas 读取文件没有分隔符和不同的列宽 - Pandas read file with no delimiter and with different column widths 如何读取具有列分隔符以及记录分隔符的csv文件 - How to read csv file which has column delimiter as well record delimiter 如何从python pandas中的列获取定界符值的右侧 - How to get right side of delimiter values from a column in python pandas 熊猫没有适当的分隔符即可读取.csv文件。 (仅第一列与“其余”分开) - pandas read .csv file without suitable delimiter. (only seperate first column vs “rest”) 如果所有值都在同一列中,如何从csv文件中读取数据? - How to read data from csv file if all the values are in the same column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM