简体   繁体   中英

How to create lists from data frames in python

My mock up data frame like...

data<-structure(list(rno = 1:8, channel = structure(c(1L, 2L, 1L, 1L, 
2L, 2L, 2L, 1L), .Label = c("AAAA", "BBBB"), class = "factor")), .Names =     c("rno", 
"channel"), class = "data.frame", row.names = c(NA, -8L))

Now I wrote a simple code to create dummy variables in R.

chan_names<-sort(as.character(unique(data[,"channel"])))
data10<-list()
for(i in 1:length(chan_names))
{
    data10[[i]]<-data[,"channel"]==chan_names[i]
}
data10<-do.call("cbind",data10)
colnames(data10)<-chan_names

Now I want to do same operation in python. I am beginner in python. help me to solve this problem. Thanks in advance.

Using pandas ,

import pandas as pd

cats = pd.Categorical((1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L), (1L, 2L))
cats.categories = ('AAAA', 'BBBB')
data = pd.DataFrame({'rno': np.arange(1,9), 'channel': cats})
#   channel  rno
# 0    AAAA    1
# 1    BBBB    2
# 2    AAAA    3
# 3    AAAA    4
# 4    BBBB    5
# 5    BBBB    6
# 6    BBBB    7
# 7    AAAA    8

data10 = pd.get_dummies(data['channel']).astype(bool)

yields

    AAAA   BBBB
0   True  False
1  False   True
2   True  False
3   True  False
4  False   True
5  False   True
6  False   True
7   True  False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM