gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:03:51 31 4
gpt4 key购买 nike

我有一个像这样的 csv 文件:

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

我想将其读入数据帧,但我希望第一个分隔符值作为一列,其余作为另一列

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. If anyone is familiar with how to do it do help me out.

最佳答案

我在 read_csv 函数中输入了错误的分隔符,这迫使 Pandas 将数据读入一列,然后我将列拆分为我想要的格式。但请注意,这并不能胜过 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

关于python - 如何从多个分隔符值中将 pandas 中的 csv 文件读取为两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60125855/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com