Skip to content

Commit

Permalink
Fix #32. Use order of primary constructor arguments to sort columns c…
Browse files Browse the repository at this point in the history
…reated in `toDataFrame()`.
  • Loading branch information
nikitinas committed Dec 14, 2021
1 parent f94086d commit 04c096d
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import kotlin.reflect.KProperty
import kotlin.reflect.KVisibility
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.primaryConstructor
import kotlin.reflect.full.withNullability
import kotlin.reflect.jvm.javaField

Expand Down Expand Up @@ -91,10 +92,12 @@ internal fun convertToDataFrame(
preserves: Set<KClass<*>>,
depth: Int
): AnyFrame {
val constructorParameters = clazz.primaryConstructor?.parameters?.mapNotNull { it.name }?.mapIndexed { i, v -> v to i }?.toMap() ?: emptyMap()

val properties = roots.ifEmpty {
clazz.memberProperties
.filter { it.visibility == KVisibility.PUBLIC && it.parameters.toList().size == 1 }
}
}.sortedBy { constructorParameters[it.name] ?: Int.MAX_VALUE }

val columns = properties.mapNotNull {
val property = it
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,14 @@ class CreateDataFrameTests {
res["d"].type() shouldBe typeOf<Int?>()
res["e"].type() shouldBe typeOf<Int>()
}

@Test
fun `preserve fields order`() {
class B(val x: Int, val c: String, d: Double) {
val b: Int = x
val a: Double = d
}

listOf(B(1, "a", 2.0)).toDataFrame().columnNames() shouldBe listOf("x", "c", "a", "b")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2183,7 +2183,7 @@ class DataFrameTests : BaseTest() {
list shouldBe df.convertTo<Target>().toList()

val listDf = list.toDataFrame()
listDf shouldBe df.reorderColumnsByName()
listDf shouldBe df
listDf.toList() shouldBe list
}

Expand All @@ -2202,7 +2202,6 @@ class DataFrameTests : BaseTest() {

val listDf = list.toDataFrame(depth = 2)
listDf shouldBe grouped.update { getFrameColumn("students") }.with { it.remove("city") }
.reorderColumnsByName()

listDf.toList() shouldBe list
}
Expand All @@ -2221,15 +2220,15 @@ class DataFrameTests : BaseTest() {
data class Info(val age: Int, val weight: Int?)

@DataSchema
data class Target(val name: String, val city: String?, val info: Info)
data class Target(val name: String, val info: Info, val city: String?)

val grouped = typed.group { age and weight }.into("info")

val list = grouped.toListOf<Target>()
list shouldBe grouped.convertTo<Target>().toList()

val listDf = list.toDataFrame(depth = 2)
listDf shouldBe grouped.reorderColumnsByName(dfs = true)
listDf shouldBe grouped
listDf.toList() shouldBe list
}

Expand Down

0 comments on commit 04c096d

Please sign in to comment.