英文:
Merge two colum of a data frame with particulars cases R
问题
You can achieve the desired result by concatenating the values from the "MANUAL.ID" and "AUTO.ID" columns into a new "species" column in your data frame. Here's an example of how to do it in Python using the pandas library:
import pandas as pd
# Create your DataFrame
data = {'MANUAL.ID': ['Barbar', 'Barbar', 'Barbar', 'Barbar', 'Pippip', ''],
'AUTO.ID': ['Barbar', '', 'Pippip', 'Pippip,Hypsav', 'Barbar', 'Barbar,Pippip']}
df = pd.DataFrame(data)
# Concatenate the values from both columns into a new 'species' column
df['species'] = df['MANUAL.ID'] + ',' + df['AUTO.ID']
# Display the resulting DataFrame
print(df[['species']])
This code will create a new "species" column in your DataFrame that contains the merged values from "MANUAL.ID" and "AUTO.ID," separated by a comma.
英文:
I have a data frame which looks like that :
MANUAL.ID | AUTO.ID |
---|---|
Barbar | Barbar |
Barbar | |
Barbar | Pippip |
Barbar | Pippip,Hypsav |
Pippip | Barbar |
Barbar,Pippip |
Basically I whould merge the both columns in a single called species and obtain this kind of result :
species |
---|
Barbar,Barbar |
Barbar |
Barbar,Pippip |
Barbar,Pippip,Hypsav |
Pippip,Barbar |
Barbar,Pippip |
What can I do to get the result ?
答案1
得分: 1
An approach using paste
with apply
data.frame(species = apply(df, 1, function(x)
ifelse(any(x == ""), paste(x, collapse=""), paste(x, collapse=","))))
species
1 Barbar,Barbar
2 Barbar
3 Barbar,Pippip
4 Barbar,Pippip,Hypsav
5 Pippip,Barbar
6 Barbar,Pippip
Data
df <- structure(list(MANUAL.ID = c("Barbar", "Barbar", "Barbar", "Barbar",
"Pippip", ""), AUTO.ID = c("Barbar", "", "Pippip", "Pippip,Hypsav",
"Barbar", "Barbar,Pippip")), row.names = c(NA, -6L), class = "data.frame")
(Note: I've translated the code part as requested.)
英文:
An approach using paste
with apply
data.frame(species = apply(df, 1, function(x)
ifelse(any(x == ""), paste(x, collapse=""), paste(x, collapse=","))))
species
1 Barbar,Barbar
2 Barbar
3 Barbar,Pippip
4 Barbar,Pippip,Hypsav
5 Pippip,Barbar
6 Barbar,Pippip
Data
df <- structure(list(MANUAL.ID = c("Barbar", "Barbar", "Barbar", "Barbar",
"Pippip", ""), AUTO.ID = c("Barbar", "", "Pippip", "Pippip,Hypsav",
"Barbar", "Barbar,Pippip")), row.names = c(NA, -6L), class = "data.frame")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论