Strings are converted to cells during readtable

110 ビュー (過去 30 日間)
Bill Tubbs
Bill Tubbs 2022 年 6 月 10 日
回答済み: Adam Danz 2024 年 1 月 4 日
I am incrementally saving data to a csv file which includes strings:
data = table("string1", "string2");
writetable(data, "data.csv");
Later on:
data_from_file = readtable('data.csv')
data_from_file =
1×2 table
Var1 Var2
___________ ___________
{'string1'} {'string2'}
Note that the data are now char arrays in cells.
This is causing lots of problems, for example when I try to join the old data with the new:
new_data = table("string1", "string2");
data = outerjoin(data_from_file, new_data, 'MergeKeys', true)
Error using tabular/outerjoin (line 152)
Left and right key variables 'Var1' and 'Var1' are not comparable because one is
a non-cell.
Is there a way to avoid this problem or convert the chars back to strings after readtable?
  2 件のコメント
KSSV
KSSV 2022 年 6 月 10 日
Show us your new_data.
Bill Tubbs
Bill Tubbs 2022 年 6 月 10 日
E.g.
new_data = table("string1", "string2");

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

採用された回答

Stephen23
Stephen23 2022 年 6 月 10 日
編集済み: Stephen23 2022 年 6 月 10 日
The simple solution is to specify the TEXTTYPE option when importing:
data = table("string1", "string2");
writetable(data, "data.csv");
data_from_file = readtable('data.csv', 'TextType','string')
data_from_file = 1×2 table
Var1 Var2 _________ _________ "string1" "string2"
  1 件のコメント
Bill Tubbs
Bill Tubbs 2022 年 6 月 10 日
Great. Thanks.

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

その他の回答 (2 件)

Adam Danz
Adam Danz 2024 年 1 月 4 日
When using the readtable(filename,opts,Name,Value) syntax, only a limited number of name-values pairs are available as input arguments and TextType is not one of them. If you are using the import options object and would like to enforce strings for text type, specify this name-value pair as an argument in detectImportOptions()
opts = detectImportOptions(filename,'TextType','string');
T = readtable(filename,opts)

KSSV
KSSV 2022 年 6 月 10 日
You can convert cell into a string and then use join.
data = table("string1", "string2");
writetable(data, "data.csv");
data_from_file = readtable('data.csv') ;
for i = 1:width(data_from_file)
data_from_file.(i) = string(data_from_file.(i)) ;
end
new_data = table("string3", "string4");
data = outerjoin(data_from_file, new_data, 'MergeKeys', true)

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by