dataframes在 Pandas 中,索引在一个或多个数字和/或字符串列中。特别是,在groupby操作之后,输出是一个数据帧,其中新索引由组给出。
同样,julia 数据框总是有一个列名Row,我认为它相当于熊猫中的索引。但是,在 groupby 操作之后,julia 数据框不使用组作为新索引。这是一个工作示例:
using RDatasets;
using DataFrames;
using StatsBase;
df = dataset("Ecdat","Cigarette");
gdf = groupby(df, "Year");
combine(gdf, "Income" => mean)
Run Code Online (Sandbox Code Playgroud)
输出:
11×2 DataFrame
? Row ? Year ? Income_mean ?
? ? Int32 ? Float64 ?
?????????????????????????????
? 1 ? 1985 ? 7.20845e7 ?
? 2 ? 1986 ? 7.61923e7 ?
? 3 ? 1987 ? 8.13253e7 ?
? 4 ? 1988 ? 8.77016e7 ?
? 5 ? 1989 ? 9.44374e7 ?
? 6 ? 1990 ? 1.00666e8 ?
? 7 ? 1991 ? 1.04361e8 ?
? 8 ? 1992 ? 1.10775e8 ?
? 9 ? 1993 ? 1.1534e8 ?
? 10 ? 1994 ? 1.21145e8 ?
? 11 ? 1995 ? 1.27673e8 ?
Run Code Online (Sandbox Code Playgroud)
即使新索引的创建不是自动完成的,我想知道是否有办法手动将所选列设置为索引。我发现了setindex!阅读文档的方法。但是,我无法使用这种方法。我试过:
#create new df
income = combine(gdf, "Income" => mean)
#set index
setindex!(income, "Year")
Run Code Online (Sandbox Code Playgroud)
这给出了错误:
ERROR: LoadError: MethodError: no method matching setindex!(::DataFrame, ::String)
Run Code Online (Sandbox Code Playgroud)
我认为我误用了命令。我在这里做错了什么?是否可以使用一个或多个选定的列在 julia 数据框中手动设置索引?
DataFrames.jl 当前不允许为数据框指定索引。该Row列仅用于打印——它实际上不是数据框的一部分。
但是,DataFrames.jl 提供了所有常用的表操作,例如连接、转换、过滤器、聚合和数据透视。对这些操作的支持不需要表索引。甲表索引是由数据库(和由大熊猫)中使用的结构,以加速某些表操作,在附加的内存使用情况的成本和创建索引的成本。
setindex!您发现的函数实际上是来自 Base Julia 的一个方法,用于自定义自定义类型的索引行为。例如,x[1] = 42相当于setindex!(x, 42, 1)。 重载此方法允许您为您创建的类型自定义索引行为。
的文档字符串Base.setindex!可以在这里和这里找到。
如果你真的需要一个带索引的表,你可以试试IndexedTables.jl。