我想选择数据框中包含列表中定义的值的所有行。 我有两种方法都无法按预期方式使用。
我的数据框看起来像这样:
Timestamp DEVICE READING VALUE
1 | DEV1 | READ1 | randomvalue
2 | DEV1 | READ2 | randomvalue
3 | DEV2 | READ1 | randomvalue
4 | DEV2 | READ2 | randomvalue
5 | DEV3 | READ1 | randomvalue
我有如下列表(ls):
[[DEV1, READ1], [DEV1, READ2], [DEV2,READ1]]
在这种情况下,我要删除行4
和5
:
我的第一个方法是:
df = df[(df['DEVICE']. isin([ls[i][0] for i in range(len(ls))])) &
(df['READING'].isin([ls[k][1] for k in range(len(ls))]))]
显然这是一个问题,它没有删除第4行,因为DEV2具有READING READ2,但是应该删除它。
我的第二种方法是:
df = df[(df[['DEVICE','READING']].isin({'DEVICE': [ls[i][0] for i in range(len(ls))],
'READING': [ls[i][1] for i in range(len(ls))] }))]
该行选择正确的行,但不会删除其他行。相反,它将所有其他单元格设置为NaN,包括我确实希望保留的VALUE ROW。而且它不会同时累积两者,因此第4行看起来像4 |DEV2|NaN|NaN
解决此问题的最简单或最佳方法是什么? 你能帮我吗?
〜法比安
答案 0 :(得分:3)
您可以将列表转换为元组列表。将数据框中的所需列转换为元组并使用isin
xsltproc normalize-space.xsl file.xml
你得到
run_some_command | xsltproc normalize-space.xsl - | xmllint --format -
答案 1 :(得分:3)
您可以使用multi-index来解决此问题。
values = [['DEV1', 'READ1'], ['DEV1', 'READ2'], ['DEV2', 'READ1']]
# DataFrame.loc requires tuples for multi-index lookups
index_values = [tuple(v) for v in values]
filtered = df.set_index(['DEVICE', 'READING']).loc[index_values].reset_index()
print(filtered)
DEVICE READING Timestamp VALUE
0 DEV1 READ1 1 randomvalue
1 DEV1 READ2 2 randomvalue
2 DEV2 READ1 3 randomvalue
答案 2 :(得分:1)
这应该做你想要的
import pandas as pd
df = pd.DataFrame({'a':[1,1,0,0,1], 'b':[0,0,1,0,1]})
keepers = [[0,0],[1,1]]
df = df[df.apply(lambda row: [row['a'], row['b']] in keepers, axis=1)]
答案 3 :(得分:0)
您为什么不这样做?
df.drop([4,5],axis=0,inplace=True)