从 pandas 中的系列中选择值
Selecting values from a series in pandas
我有一个数据集 D,其中包含来自 [A - Z] 的列,共 26 列。我做了一些测试,知道了S系列中哪些是对我有用的专栏。
D #Dataset with columns from A - Z
S
B 0.78
C 1.04
H 2.38
S 有列和与之关联的值,所以我现在知道它们的重要性,并且只想保留数据集中的那些列,例如(B
、C
、D
) 我该怎么做?
IIUC 你可以使用:
cols = ['B','C','D']
df = df[cols]
或者如果列名在 Series
中作为值:
S = pd.Series(['B','C','D'])
df = df[S]
样本:
df = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
print (df)
A B C D E F
0 1 4 7 1 5 7
1 2 5 8 3 3 4
2 3 6 9 5 6 3
S = pd.Series(['B','C','D'])
print (S)
0 B
1 C
2 D
dtype: object
print (df[S])
B C D
0 4 7 1
1 5 8 3
2 6 9 5
或index
值:
S = pd.Series([1,2,3], index=['B','C','D'])
print (S)
B 1
C 2
D 3
dtype: int64
print (df[S.index])
B C D
0 4 7 1
1 5 8 3
2 6 9 5
我有一个数据集 D,其中包含来自 [A - Z] 的列,共 26 列。我做了一些测试,知道了S系列中哪些是对我有用的专栏。
D #Dataset with columns from A - Z
S
B 0.78
C 1.04
H 2.38
S 有列和与之关联的值,所以我现在知道它们的重要性,并且只想保留数据集中的那些列,例如(B
、C
、D
) 我该怎么做?
IIUC 你可以使用:
cols = ['B','C','D']
df = df[cols]
或者如果列名在 Series
中作为值:
S = pd.Series(['B','C','D'])
df = df[S]
样本:
df = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
print (df)
A B C D E F
0 1 4 7 1 5 7
1 2 5 8 3 3 4
2 3 6 9 5 6 3
S = pd.Series(['B','C','D'])
print (S)
0 B
1 C
2 D
dtype: object
print (df[S])
B C D
0 4 7 1
1 5 8 3
2 6 9 5
或index
值:
S = pd.Series([1,2,3], index=['B','C','D'])
print (S)
B 1
C 2
D 3
dtype: int64
print (df[S.index])
B C D
0 4 7 1
1 5 8 3
2 6 9 5