I am trying to implement the same python code for the following r code:
nm <- c("Sepal.Length" ,"Sepal.Width" , "Petal.Length", "Petal.Width", "Species")
nm_data <-
sapply(1:length(nm), function(i)
c(nm[-(0:i)], nm[0:i])) %>% data.frame()
comb_predictors <- list()
for (i in 1:length(nm_data)) {
comb_predictors[[i]] <- nm_data[1:i, ]
}
It should move the first element in the list one row down, and for each column until the last column when it returns to the beginning.
As for nm_data
, I have tried the following python attempt:
import pandas as pd
import numpy as np
nm = ["Sepal.Length" ,"Sepal.Width" , "Petal.Length", "Petal.Width", "Species"]
def tbl(data, x):
df=np.transpose((data[::-x], data[0:x]))
return(pd.DataFrame(df))
cnt = [x for x in range(0, len(nm))]
list(map(tbl, nm, cnt))
However, I get the following result:
[ 0
0
1 ,
0
0 S
1 S,
0
0 Pe
1 Pe,
0
0 Pet
1 Pet,
0
0 Spec
1 Spec]
If I do
tbl(nm, 1)
0 1
0 Species Sepal.Length
1 Petal.Width Sepal.Width
2 Petal.Length Petal.Length
3 Sepal.Width Petal.Width
4 Sepal.Length Species
however, I cannot get it like the expected output. I know that for comb_predictors
I just run it in a for loop so thats easy enough to get. But I am having trouble with getting nm_data
with python.
My expected result:
1 Sepal.Width Petal.Length Petal.Width Species Sepal.Length
2 Petal.Length Petal.Width Species Sepal.Length Sepal.Width
3 Petal.Width Species Sepal.Length Sepal.Width Petal.Length
4 Species Sepal.Length Sepal.Width Petal.Length Petal.Width
5 Sepal.Length Sepal.Width Petal.Length Petal.Width Species
CodePudding user response:
You overcomplicated it - you need only
data = [nm[x:] nm[:x] for x in range(1, len(nm) 1)]
And eventually later you can convert it to DataFrame
Minimal working code
import pandas as pd
nm = ["Sepal.Length" ,"Sepal.Width" , "Petal.Length", "Petal.Width", "Species"]
data = [nm[x:] nm[:x] for x in range(1, len(nm) 1)]
df = pd.DataFrame(data)
print(df)
Result:
0 1 2 3 4
0 Sepal.Width Petal.Length Petal.Width Species Sepal.Length
1 Petal.Length Petal.Width Species Sepal.Length Sepal.Width
2 Petal.Width Species Sepal.Length Sepal.Width Petal.Length
3 Species Sepal.Length Sepal.Width Petal.Length Petal.Width
4 Sepal.Length Sepal.Width Petal.Length Petal.Width Species
EDIT:
You can also use collections.deque()
to rotate list:
import pandas as pd
import collections
nm = ["Sepal.Length" ,"Sepal.Width" , "Petal.Length", "Petal.Width", "Species"]
data = []
d = collections.deque(nm)
for _ in range(len(nm)):
d.rotate(-1)
data.append(list(d))
#print(list(d))
df = pd.DataFrame(data)
print(df)