Pandas 熊猫:按整数选择dataframe中的多个列
假设我有这个数据帧:Pandas 熊猫:按整数选择dataframe中的多个列,pandas,dataframe,subset,Pandas,Dataframe,Subset,假设我有这个数据帧: df = pd.DataFrame({'a' : (1, 2, 3), 'b' : (1, 2, 3), 'c' : ("one", "two", "three"), 'd' : (4, 5, 6), 'e' : (4, 5, 6),
df = pd.DataFrame({'a' : (1, 2, 3),
'b' : (1, 2, 3),
'c' : ("one", "two", "three"),
'd' : (4, 5, 6),
'e' : (4, 5, 6),
'f' : (7, 8, 9),
'g' : (7, 8, 9),
'h' : (7, 8, 9)})
我正在尝试选择第一、第三和第五列,直到最后一列。预期的产出将是:
a c e f g h
0 1 one 4 7 7 8
1 2 two 5 8 7 8
2 3 three 6 9 9 9
如何使用integer选择不连续的多个列?我尝试了以下方法:
df.iloc[,[0, 3, 5:]]
df.loc[,[0, 3, 5:]]
df.iloc[,[0, 3, 5:len(df.columns)]]
df.loc[,[0, 3, 5:len(df.columns)]]
df.iloc[,[0 + 3 + 5:]]
df.loc[,[0 + 3 + 5:]]
df.iloc[,[0 + 3 + 5:len(df.columns)]]
df.loc[,[0 + 3 + 5:len(df.columns)]]
都不管用
请建议用于联接切片器,python计数从0
开始,因此对于第三列需要2
和第五列需要4:
:
df = df.iloc[:, np.r_[0, 2, 4:len(df.columns)]]
print (df)
a c e f g h
0 1 one 4 7 7 7
1 2 two 5 8 8 8
2 3 three 6 9 9 9
你也可以用你喜欢的方式将列表展平
从pandas.core.common导入展平
df1=df.iloc[:,list(展平([[0,2],范围(4,len(df.columns)))]
df2=df.iloc[:,np.concatenate([[0,2],range(4,len(df.columns))])]
Lifesaver,如果你不介意的话,你还有通过df.values
转换numpy数据的解决方案吗?@AgnesLee-你认为a=df.to_numpy()
然后arr=a[:,np.r\0,2,4:a.shape[1]]
?