11[ // ] : # ( title: convertTo )
22<!-- -IMPORT org.jetbrains.kotlinx.dataframe.samples.api.Modify-->
33
4- [ Converts] ( convert.md ) columns in [ ` DataFrame ` ] ( DataFrame.md ) to match a given schema [ ` Schema ` ] ( schema.md ) .
4+ [ Converts] ( convert.md ) all columns in the [ ` DataFrame ` ] ( DataFrame.md ) to match a given schema [ ` Schema ` ] ( schema.md ) .
55
66``` kotlin
77convertTo<Schema >(excessiveColumns = ExcessiveColumns .Keep )
88```
99
10- ** Related operations** : [ ] ( adjustSchema.md )
10+ ** Related operations** : [ ] ( adjustSchema.md ) , [ ] ( convert.md )
11+
12+ Conversion to match the target schema is done mostly automatically;
13+ DataFrame knows how to convert between many types (see [ ] ( convert.md ) for details and the supported types).
14+
15+ However, if you have a custom type in your target schema, or the automatic conversion fails,
16+ you can provide a custom converter, parser, or filler for it.
17+ These have priority over the automatic ones.
1118
1219Customization DSL:
13- * ` convert ` —how specific column types should be converted
14- * ` parser ` —how to parse strings into custom types
15- * ` fill ` —how to fill missing columns
20+ * ` convert<A>.with { it.toB() } `
21+ * Provides ` convertTo<>() ` with the knowledge of how to convert ` A ` to ` B `
22+ * ` parser { YourType.fromString(it) } `
23+ * Provides ` convertTo<>() ` with the knowledge of how to parse strings/chars into ` YourType `
24+ * Shortcut for ` convert<String>().with { YourType.fromString(it) } `
25+ * Chars are treated as strings unless you explicitly specify ` convert<Char>().with { YourType.fromChar(it) } `
26+ * ` fill { some cols }.with { rowExpression } `
27+ * Makes ` convertTo<>() ` fill missing (or existing) columns from the target schema
28+ with values computed by the given row expression
1629
1730<!-- -FUN customConvertersData-->
1831
@@ -27,11 +40,17 @@ class MySchema(val a: MyType, val b: MyType, val c: Int)
2740<!-- -FUN customConverters-->
2841
2942``` kotlin
30- val df = dataFrameOf(" a" , " b" )(1 , " 2" )
43+ val df: AnyFrame = dataFrameOf(
44+ " a" to columnOf(1 , 2 , 3 ),
45+ " b" to columnOf(" 1" , " 2" , " 3" ),
46+ )
3147df.convertTo<MySchema > {
32- convert<Int >().with { MyType (it) } // converts `a` from Int to MyType
33- parser { MyType (it.toInt()) } // converts `b` from String to MyType
34- fill { c }.with { a.value + b.value } // computes missing column `c`
48+ // providing the converter: Int -> MyType, so column `a` can be converted
49+ convert<Int >().with { MyType (it) }
50+ // providing the parser: String -> MyType, so column `b` can be converted
51+ parser { MyType (it.toInt()) }
52+ // providing the filler for `c`, as it's missing in `df`
53+ fill { c }.with { a.value + b.value }
3554}
3655```
3756
0 commit comments