我有一个文件,其中包含如下数据

1000000 183:0.6673;2:0.3535;359:0.304;363:0.1835
1000001 92:1.0
1000002 112:1.0
1000003 154435:0.746;30:0.3902;220:0.2803;238:0.2781;232:0.2717
1000004 118:1.0
1000005 157:0.484;25:0.4383;198:0.3033
1000006 277:0.7815;1980:0.4825;146:0.175
1000007 4069:0.6678;2557:0.6104;137:0.4261
1000009 2:1.0

我想将文件读取到由多个分隔符 \t, :, ; 分隔的 Pandas 数据框

我试过了
df_user_key_word_org = pd.read_csv(filepath+"user_key_word.txt", sep='\t|:|;', header=None, engine='python')
它给了我以下错误。
pandas.errors.ParserError: Error could be due to quotes being ignored when a multi-char delimiter is used.
为什么我收到这个错误?

所以我想我会尝试使用正则表达式字符串。但我不确定如何编写拆分正则表达式。 r'\t|:|;'不起作用。

将文件读取到具有多个分隔符的 Pandas 数据框的最佳方法是什么?

最佳答案

从这个问题 Handling Variable Number of Columns with Pandas - Pythonpandas.errors.ParserError: Expected 29 fields in line 11, saw 45. 的一种解决方法是让 read_csv 提前知道有多少列。

my_cols = [str(i) for i in range(45)] # create some col names
df_user_key_word_org = pd.read_csv(filepath+"user_key_word.txt",
                                   sep="\s+|;|:",
                                   names=my_cols,
                                   header=None,
                                   engine="python")
# I tested with s = StringIO(text_from_OP) on my computer
pandas read_csv() 用于多个分隔符-LMLPHP
希望这有效。

关于pandas read_csv() 用于多个分隔符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48063620/

10-15 01:02
查看更多