I want to get the columns names of a Data Frame with the following code:
DF <- data.frame(X=c(1,2), Y=c(3,4))
as.character(sapply(DF, names))
I've got the following:
"NULL" "NULL"
but I need the following result:
"X" "Y"
How can I do this, thanks in advance.
You can get the column names from pandas DataFrame using df. columns. values , and pass this to python list() function to get it as list, once you have the data you can print it using print() statement.
To access a specific column in a dataframe by name, you use the $ operator in the form df$name where df is the name of the dataframe, and name is the name of the column you are interested in. This operation will then return the column you want as a vector.
You can use the loc and iloc functions to access columns in a Pandas DataFrame. Let's see how. If we wanted to access a certain column in our DataFrame, for example the Grades column, we could simply use the loc function and specify the name of the column in order to retrieve it.
The column items in a data frame in R can be accessed using: Single brackets [] , which would display them as a column. Double brackets [[]] , which would display them as a list.
But there's a function to do it directly. See ?colnames
colnames(DF)
[1] "X" "Y"
In this case you could also do
names(DF)
[1] "X" "Y"
either way you don't need sapply
to extract the column names.
If you name the rows names
still only gives the column names:
rownames(DF)<-list("a","b")
DF
X Y
a 1 3
b 2 4
names(DF)
[1] "X" "Y"
but the rownames
function gets the row names for you:
rownames(DF)
[1] "a" "b"
If you had a list of data frames with the same number of columns you might perhaps use sapply
with names
.
If you want to obtain both the row and column names of the data frame, see dimnames
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With