reading CSV files with multiple rows of strings and multiple rows of floats

6 views (last 30 days)
The first four rows [1:4] of my csv are strings. The remaining rows [5:inf] are numerical data. I need to import all rows, preferably into a table. How can I do this with readtable (or other function). I don't see any way in the opts file. I am probably missing something.

Answers (2)

Steven Lord
Steven Lord on 11 Aug 2025
All the data in a variable in a table must be the same type. You can't have one where the first four rows are text and the next four rows are numbers.
Depending on what you're planning to do, reading the first four rows into a table then reading in the next rows as a separate table, transforming each row of each of those tables into variables using rows2vars, and then concatenating them side-by-side may be suitable for your needs.
t1 = table("abc", "def", "ghi", "jkl", RowNames = "id")
t1 = 1×4 table
Var1 Var2 Var3 Var4 _____ _____ _____ _____ id "abc" "def" "ghi" "jkl"
t2 = array2table(magic(4))
t2 = 4×4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1
t1a = rows2vars(t1)
t1a = 4×2 table
OriginalVariableNames id _____________________ _____ {'Var1'} "abc" {'Var2'} "def" {'Var3'} "ghi" {'Var4'} "jkl"
t2a = rows2vars(t2)
t2a = 4×5 table
OriginalVariableNames Var1 Var2 Var3 Var4 _____________________ ____ ____ ____ ____ {'Var1'} 16 5 9 4 {'Var2'} 2 11 7 14 {'Var3'} 3 10 6 15 {'Var4'} 13 8 12 1
T = [t1a(:, "id"), t2a(:, 2:end)]
T = 4×5 table
id Var1 Var2 Var3 Var4 _____ ____ ____ ____ ____ "abc" 16 5 9 4 "def" 2 11 7 14 "ghi" 3 10 6 15 "jkl" 13 8 12 1

Kip
Kip on 11 Aug 2025
Thanks to all for these hints. Trouble is, at the end I need to write these back to a file of the same format (columns with a mixture of characters and numerical values). I found I can do this pretty easily with Python and will go with that. Thank you!

Categories

Find more on Data Import from MATLAB in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!