当读取从文本文件列表到pandas dataframe列的列表时,面对`parserError:错误标记数据。 C错误:预期在第3行中的16个字段,看到21`

发布于 2025-02-11 15:21:23 字数 504 浏览 2 评论 0原文

我有一个称为tropical.txt的文本文件,该文件具有多个列表,看起来像这样,

['papaya', 'mangosteen', 'banana']
[]
['coconut', 'mango']

我该如何将其读取到pandas dataframe中,从而使我的最终输出看起来像这样? 水果是我预期输出中的列名。

  fruits
0 [apple, orange, banana]
1 []
2 [pineapple, mango]


我尝试了

pd.read_csv('tropical.txt')

,但这给了我解析错误

ParserError: Error tokenizing data. C error: Expected 16 fields in line 3, saw 21

I have a text file called tropical.txt that have multiple lists that looks like this

['papaya', 'mangosteen', 'banana']
[]
['coconut', 'mango']

How can I read it into a pandas dataframe such that my final output will look like this? fruits is my column name in the expected output.

  fruits
0 [apple, orange, banana]
1 []
2 [pineapple, mango]


I tried

pd.read_csv('tropical.txt')

But it's giving me a parse error

ParserError: Error tokenizing data. C error: Expected 16 fields in line 3, saw 21

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷乱花海 2025-02-18 15:21:23

CSV是逗号分隔的值,因此Pandas将列表中的每个逗号视为列分隔符。您应该尝试更改sep参数pd.read_csv

CSV is comma-separated values, so pandas is treating every comma in your list as a column separator. You should try and change the sep argument in pd.read_csv

卖梦商人 2025-02-18 15:21:23

df = pd.read_csv('tropical.txt', sep="\n")

阅读到熊猫数据框后,将字符串转换为列表。

df[0] = df[0].apply(eval)


df = pd.read_csv('tropical.txt', sep="\n")

After reading into the pandas dataframe, convert the string into a list.

df[0] = df[0].apply(eval)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文