I am trying to select different columns and rows in dataframe Here are some examples
df1 = DataFrame(np.random.randn(6,4), index=list('abcdef'), columns=list('ABCD'))
A B C D
a -0.767663 0.158213 0.502184 0.156238
b -0.450274 -0.287952 -0.666661 -0.934083
c 2.142362 -1.212363 0.075363 -0.270905
d 0.075977 1.355053 -1.665973 1.266896
e -1.251002 0.274878 -0.511252 1.734822
f -0.587612 0.731301 -0.680246 0.286389
Example 1:
df1.loc[['a','b','d'],:]
A B C D
a -0.767663 0.158213 0.502184 0.156238
b -0.450274 -0.287952 -0.666661 -0.934083
d 0.075977 1.355053 -1.665973 1.26689
Example2:
df1.loc[['a','b'],:'B']
A B
a -0.767663 0.158213
b -0.450274 -0.2879520
Example3:
df1.loc['d':,'A':'C']
A B C
d 0.075977 1.355053 -1.665973
e -1.251002 0.274878 -0.511252
f -0.587612 0.731301 -0.680246
Example4:
df1.loc[['d','e'],:'A']
A
d 0.075977
e -1.251002
Example5:
df1.loc[['a','d'],:['B','D']] ==> not a valid syntax
Error:IndexError: invalid slice
Any hints on how to select columns B and D for rows a and d
Just do this way :
df1.loc[['a','d'],['B','D']]
i:j
means you want a slice from i to j (like in your example 3)
Here you don't want a slice so you don't need :
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.