read csv with negative values (blank space between number and minus)

23 ビュー (過去 30 日間)
Sara Schulz
Sara Schulz 2023 年 5 月 16 日
編集済み: Sara Schulz 2023 年 5 月 16 日
Hi everyone!
I want to simply read the values in a csv file into an array. The function readtable works good. I only have the issue that some values are negative numbers but not for example -9 but with a blank space like - 9. So the functions reads it at NaN.
I did this:
mydata = readtable("mytable.csv");
Does anybody have an idea how I could still get the right values for the negative ones? Do I have to remove all the blank spaces somehow?
Thank you for any help and all the best,
Sara
  2 件のコメント
Stephen23
Stephen23 2023 年 5 月 16 日
"Do I have to remove all the blank spaces somehow?"
How many files do you have like this?
If there are only a handful, then use find-and-replace of any reputable text editor (e.g. Notepad++).
Askic V
Askic V 2023 年 5 月 16 日
We need to know how your csv file looks like. I think your problem is due to default limiter in the function readtable.
To my knowledge, default delimiter is any whitespace character and perhaps, this is a reason why you get NaN.

サインインしてコメントする。

回答 (2 件)

Sara Schulz
Sara Schulz 2023 年 5 月 16 日
編集済み: Sara Schulz 2023 年 5 月 16 日
You have to use the following code to delete all blank spaces in the csv:
chr = fileread('myfile.csv');
chr = strrep(chr, ' ', '');
fid = fopen('myfile.csv', 'w');
fprintf(fid, '%s', chr);
fclose(fid);

Shaik
Shaik 2023 年 5 月 16 日
Hi Sara!
To address the issue with negative numbers in your CSV file that have a blank space before the negative sign (e.g., "- 9" instead of "-9"), you can preprocess the data before reading it into the table. One approach is to remove the blank spaces from the values before parsing them.

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

製品


リリース

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by