Skip to content

Commit abdfea1

Browse files
committed
Convert one DataFrame to other or copy dataframes
Signed-off-by: Aravinda VK <vkaravinda7@gmail.com>
1 parent ff17469 commit abdfea1

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,3 +207,21 @@ foreach (record;file.byLine.joiner("\n").csvReader!ItemCsvData(header: null))
207207
// Preview the imported data
208208
df.writeln;
209209
```
210+
211+
## Copying the DataFrame or creating DataFrame of new Type
212+
213+
To create a `PriceList` dataframe from the list of items.
214+
215+
```d
216+
struct PriceList
217+
{
218+
string name;
219+
double price;
220+
}
221+
222+
df.rows
223+
.sort!("a.name < b.name")
224+
.uniq!("a.name == b.name")
225+
.to_df!PriceList
226+
.writeln;
227+
```

source/dataframes/package.d

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,20 @@ class DataFrame(T)
199199

200200
return output.data;
201201
}
202+
203+
DataFrame!T to_df()
204+
{
205+
return to_df!T;
206+
}
207+
208+
DataFrame!T1 to_df(T1)()
209+
{
210+
auto output = new DataFrame!T1;
211+
foreach(r; this.rows)
212+
output.add(r.toDataFrameStruct!T1);
213+
214+
return output;
215+
}
202216
}
203217

204218
unittest
@@ -285,4 +299,27 @@ unittest
285299
assert(result[3].name == "C");
286300
assert(result[4].name == "D");
287301
assert(result[5].name == "E");
302+
303+
struct PriceList
304+
{
305+
string name;
306+
double price;
307+
}
308+
309+
auto items = df.rows
310+
.sort!("a.name < b.name")
311+
.uniq!("a.name == b.name")
312+
.to_df!PriceList;
313+
314+
assert(items.length == 5);
315+
assert(items.ncol == 2);
316+
assert(items.columnNames == ["name", "price"]);
317+
318+
auto dfCopy = df.to_df;
319+
assert(dfCopy.ncol == 4);
320+
assert(dfCopy.nrow == 6);
321+
322+
auto itemsDf = df.to_df!PriceList;
323+
assert(itemsDf.ncol == 2);
324+
assert(itemsDf.nrow == 6);
288325
}

source/dataframes/rows.d

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,28 @@ struct Row(T)
4444

4545
return output.data ~ ")";
4646
}
47+
48+
T1 toDataFrameStruct(T1)()
49+
{
50+
alias outputFieldNames = FieldNameTuple!(T1);
51+
T1 output;
52+
53+
static foreach(name; outputFieldNames)
54+
{
55+
static if(hasMember!(T, name))
56+
__traits(getMember, output, name) = __traits(getMember, this, name);
57+
}
58+
59+
return output;
60+
}
61+
}
62+
63+
DataFrame!T to_df(T, Range)(Range rows)
64+
{
65+
auto df = new DataFrame!T;
66+
67+
foreach(row; rows)
68+
df.add(row.toDataFrameStruct!T);
69+
70+
return df;
4771
}

0 commit comments

Comments
 (0)