【问题标题】:How to subset a DataFrame by only a column having multiple entries?如何仅通过具有多个条目的列对 DataFrame 进行子集化?
【发布时间】:2017-06-08 00:31:43
【问题描述】:
我有一个看起来像这样的 pandas DataFrame df:
0 1
C1 V1
C2 V1
C3 V1
C4 V2
C5 V3
C6 V3
C7 V4
我希望仅将df 子集化为1 列中具有多个值的行,所需的输出为:
0 1
C1 V1
C2 V1
C3 V1
C5 V3
C6 V3
我该怎么做?
【问题讨论】:
标签:
python-3.x
pandas
dataframe
【解决方案1】:
我认为您需要boolean indexing 和DataFrame.duplicated 创建的掩码和keep=False 将所有重复项标记为True:
print (df.columns)
Index(['0', '1'], dtype='object')
mask = df.duplicated('1', keep=False)
#another solution with Series.duplicated
#mask = df['1'].duplicated(keep=False)
print (mask)
0 True
1 True
2 True
3 False
4 True
5 True
6 False
dtype: bool
print (df[mask])
0 1
0 C1 V1
1 C2 V1
2 C3 V1
4 C5 V3
5 C6 V3
print (df.columns)
Int64Index([0, 1], dtype='int64')
mask = df.duplicated(1, keep=False)
#another solution with Series.duplicated
#mask = df[1].duplicated(keep=False)
print (mask)
0 True
1 True
2 True
3 False
4 True
5 True
6 False
dtype: bool
print (df[mask])
0 1
0 C1 V1
1 C2 V1
2 C3 V1
4 C5 V3
5 C6 V3