我正在使用合并两个数据帧pandas.merge.即使在指定how = left选项后,我发现合并数据帧的行数大于原始行.为什么会这样?
panel = pd.read_csv(file1, encoding ='cp932')
before_len = len(panel)
prof_2000 = pd.read_csv(file2, encoding ='cp932').drop_duplicates()
temp_2000 = pd.merge(panel, prof_2000, left_on='Candidate_u', right_on="name2", how="left")
after_len = len(temp_2000)
print(before_len, after_len)
> 12661 13915
Run Code Online (Sandbox Code Playgroud) 我的数据集有这些变量:
> colnames(sample)
[1] "gender" "age" "partyID"
[4] "treatment_rand" "treatment_bias" "y_randT"
[7] "y_biasT" "y_randConti" "y_biasConti"
[10] "factor.sample.partyID.1" "factor.sample.partyID.2" "factor.sample.partyID.3"
[13] "factor.sample.partyID.4" "factor.sample.partyID.5" "factor.sample.partyID.6"
[16] "factor.sample.partyID.7" "factor.sample.partyID.8"
Run Code Online (Sandbox Code Playgroud)
我想factor.sample.从所有列中删除。我尝试了这段代码,但出现错误。
> sample %>%
+ rename_(.dots=setNames(names(.), gsub("factor\\.sample\\.", "", names(.))))
Error in select_impl(.data, vars) :
found duplicated column name: factor.sample.partyID.1, factor.sample.partyID.2, factor.sample.partyID.3, factor.sample.partyID.4, factor.sample.partyID.5, factor.sample.partyID.6, factor.sample.partyID.7, factor.sample.partyID.8
Run Code Online (Sandbox Code Playgroud)
我该如何使用 来做到这一点dplyr?
我想将列中的所有NA更改为0.我可以使用mutate(),但不能使用mutate_if().
这有效:
> test <- tibble(Q3.2 = c(1,2, NA, NA, 3),
Q8.2 = c(2, NA, 1, NA, 4))
> test %>% select_("Q3.2", "Q8.2") %>%
mutate(Q3.2 = ifelse(is.na(Q3.2), 0, Q3.2),
Q8.2 = ifelse(is.na(Q8.2), 0, Q8.2))
Run Code Online (Sandbox Code Playgroud)
但这不是:
> test %>% select_("Q3.2", "Q8.2") %>%
+ mutate_if(is.na(.), 0, .)
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'p' of mode 'function' was not found
Run Code Online (Sandbox Code Playgroud)