英文:
Can't Change Column Names with $
问题
我已经检查了与此问题相关的其他问题,但没有一个解决方案有效(https://stackoverflow.com/questions/6081439/changing-column-names-of-a-data-frame,https://stackoverflow.com/questions/11346283/renaming-column-names-in-pandas)
我有一个数据框,在其中使用索引将数据框合并在一起。这很好用,除了数据框上的新列标题喜欢在新列中重复名称。例如:我希望主数据框中的新列显示为“LiveDemand”,但实际上它显示为“LiveDemand$LiveDemand”。
然后,我尝试使用colnames()将列头替换为新名称。我没有错误,但当我检查数据框时,名称未更改。有人能帮忙解释为什么吗?以下是我的代码:
mainDF$LiveDemand <- DemandDF[DemandIndexes, "LiveDemand"]
# 结果是一个名为'LiveDemand$LiveDemand'的新列
colnames(mainDF)[which(names(mainDF) == "LiveDemand$LiveDemand")] <- "LiveDemand"
# 我也尝试过
colnames(mainDF)[18] <- "LiveDemand"
# 这个也试过
mainDF<- rename(mainDF, LiveDemand= "LiveDemand")
这三种方法都没有错误,但是列头没有更改(任何一种方法都没有)。真正奇怪的是当我使用rename时,如果我说旧的列名是“LiveDemand$LiveDemand”,它会给我一个错误,说它不存在,但是当我查看数据框时,它明显显示为“LiveDemand$LiveDemand”。
有什么想法吗?
英文:
I've checked the other questions related to this issue but none of the solutions worked (https://stackoverflow.com/questions/6081439/changing-column-names-of-a-data-frame, https://stackoverflow.com/questions/11346283/renaming-column-names-in-pandas)
I have a data frame where I use indexes to merge data frames together. That works fine, except the new column headers on the data frame likes to double the name in the new column. For example: I expect the new column in the main data frame to say "LiveDemand" but instead it says "LiveDemand$LiveDemand".
I then try to use colnames() to replace the column header to a new name. I get no errors, but when I check the data frame the name is unchanged. Can anyone help explain why? Here is my code:
mainDF$LiveDemand <- DemandDF[DemandIndexes, "LiveDemand"]
#Result is a new column called 'LiveDemand$LiveDemand'
colnames(mainDF)[which(names(mainDF) == "LiveDemand$LiveDemand")] <- "LiveDemand"
#I've also tried
colnames(mainDF)[18] <- "LiveDemand"
#This as well
mainDF<- rename(mainDF, LiveDemand= "LiveDemand")
All three methods give no errors, but the column header doesn't change (none of them do). What is really strange is when I use rename, if I say the old column name is "LiveDemand$LiveDemand" it gives me an error saying it doesn't exist, but when I go to view the data frame, it clearly says "LiveDemand$LiveDemand".
Any ideas?
答案1
得分: 1
用$
直接提取列作为向量,然后使用索引进行子集操作,避免使用drop
参数(对于data.frame是TRUE
,对于data.table/tibble是FALSE
,即在data.frame中,当有单行或单列时,它会将其强制转换为向量,而在tibble、data.table中,它仍然是一个只有单列的tibble/data.table)。
mainDF$LiveDemand <- DemandDF$LiveDemand[DemandIndexes]
英文:
It may be better to directly extract the column as vector with $
and then subset using the index, thus avoiding the drop
argument value (which is TRUE
- for data.frame and FALSE
for data.table/tibble - i.e. it coerce to a vector when there is a single row or single column in data.frame, whereas in tibble, data.table, it will still be a tibble/data.table with a single column)
mainDF$LiveDemand <- DemandDF$LiveDemand[DemandIndexes]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论