Julia按前一列

时间:2016-01-23 07:02:30

标签: julia

我有一个有3列的数据框 年龄,性别和比率

see dataframe

我想阅读" Rate"通过引用前两列 说,(3,M)将返回0.0001885

朱莉娅有没有聪明的方法呢?

(我希望解决方案可以是通用的,无论我需要多少索引列,解决方案都可以处理此问题)

2 个答案:

答案 0 :(得分:3)

创建示例DataFrame

julia> df = DataFrame(Age = rand(1:100,10), Sex = rand(['M','F'],10), Rate = ran
d(10))
10x3 DataFrames.DataFrame
| Row | Age | Sex | Rate       |
|-----|-----|-----|------------|
| 1   | 2   | 'F' | 0.0125987  |
| 2   | 81  | 'F' | 0.0538013  |
| 3   | 3   | 'M' | 0.885425   |
| 4   | 92  | 'M' | 0.00412666 |
| 5   | 70  | 'M' | 0.113444   |
| 6   | 37  | 'M' | 0.845769   |
| 7   | 47  | 'M' | 0.234437   |
| 8   | 68  | 'M' | 0.791475   |
| 9   | 46  | 'M' | 0.831009   |
| 10  | 30  | 'M' | 0.812764   |

根据多种条件选择行:

julia> df[(df[:Age].==47) & (df[:Sex].=='M'),:]
1x3 DataFrames.DataFrame
| Row | Age | Sex | Rate     |
|-----|-----|-----|----------|
| 1   | 47  | 'M' | 0.234437 |

按ID选择列:

julia> df[(df[:Age].>47) & (df[:Sex].=='M'),3]
3-element DataArrays.DataArray{Float64,1}:
 0.00412666
 0.113444
 0.791475

选择最后一栏:

julia> df[(df[:Age].>47) & (df[:Sex].=='M'),end]
3-element DataArrays.DataArray{Float64,1}:
 0.00412666
 0.113444
 0.791475

选择多列:

julia> df[(df[:Age].>47) & (df[:Sex].=='M'),[1,3]]
3x2 DataFrames.DataFrame
| Row | Age | Rate       |
|-----|-----|------------|
| 1   | 92  | 0.00412666 |
| 2   | 70  | 0.113444   |
| 3   | 68  | 0.791475   |

也可以使用列符号进行相同的操作,例如: :Rate代替id。

答案 1 :(得分:1)

如果每次都通过相同的列访问DataFrame,则从索引到值的Dict是更快(也许更干净)的解决方案。为了澄清,在你的例子中,它会像:

df = DataFrame(Age=[0,1,2,3,4,5,6],
               Sex=UTF8String["M","M","M","M","M","M","M"],
               Rate=[0.0031934,0.0002601,0.0002215,
                     0.0001885,0.000161,0.0001391,0.0001226])

# define Dict from :Age,:Sex => :Rate
d = Dict(zip((zip(df[:Age],df[:Sex])),df[:Rate]))

# now we have:
d[(3,"M")] == 0.0001885
d[(0,"M")] == 0.0031934

可以为其他访问组合生成其他Dicts。这类似于在数据库上创建索引 - 使用模式,时间和内存约束应指导解决方案选择。