操作列

Julia 中的数据操作

Katerina Zahradova

Instructor

应用函数

  • 处理整列的函数

    • 由整列决定的特征,如均值、最小值等
    • 在 Julia 中,maximum() 等函数需写全称,不是 max()
  • 处理单行的函数

Julia 中的数据操作

选项

  • select()

  • transform()

  • combine()

就地修改 DataFrame:

  • select!(), transform!(), combine!()
Julia 中的数据操作

select()

# 选择列
select(penguins, :species, :body_mass_g)
333x2 DataFrame
Row species   body_mass_g
    String15  Int64
___________________________
1   Adelie    3750
2   Adelie    3800
3   Adelie    3250
...
# 选择并重命名列
select(penguins, :species, :body_mass_g => :weight_g)
333x2 DataFrame
Row species   weight_g
    String15  Int64
___________________________
1   Adelie    3750
2   Adelie    3800
3   Adelie    3250
...
Julia 中的数据操作

select()

# 选择列并应用函数
select(penguins, :species, :body_mass_g => mean)
333x2 DataFrame
Row species   body_mass_g_mm
    String15  Float64
___________________________
1   Adelie    4207.06
2   Adelie    4207.06
3   Adelie    4207.06
...
Julia 中的数据操作

transform()

# 添加 body_mass_g 的最大值列
transform(penguins, :body_mass_g => maximum)
333x8 DataFrame
Row species   island    ...  body_mass_g  sex      body_mass_g_maximum
    String15  String15  ...  Int64        String7  Float64 
___________________________________________________________________
1   Adelie    Torgersen ...  3750         MALE     4207.06
2   Adelie    Torgersen ...  3800         FEMALE   4207.06
...
Julia 中的数据操作

combine()

# 将 penguins 与 body_mass_g 的最大值合并
combine(penguins, :body_mass_g => maximum)
1×1 DataFrame
Row  body_mass_g_mean
     Float64
__________________________
1    4207.06

Julia 中的数据操作

处理多个的方式

# 对一列使用多个函数
combine(penguins, :body_mass_g .=> [mean, minimum, maximum])
Row  body_mass_g_mean  body_mass_g_minimum  body_mass_g_maximum
     Float64           Float64              Float64       
_______________________________________________________________
1    4207.06           2700                 6300
# 传入多列给一个函数
select(penguins, [:body_mass_g, :flipper_length_mm] .=> mean)
Row  body_mass_g_mean  flipper_length_mm_mean  
     Float64           Float64              
___________________________________________
1    4207.06           200.967               
2    4207.06           200.967   
...
Julia 中的数据操作

速查表

  • select()

    • 仅包含指定列
    • 行数不变;相同值广播到所有行
  • transform()

    • 保留所有列并新增列
    • 行数不变;相同值广播到所有行
  • combine()

    • 仅包含指定列
    • 不会将值广播到所有行
Julia 中的数据操作

Passons à la pratique !

Julia 中的数据操作

Preparing Video For Download...