簡體   English   中英

如何識別指定列范圍內的某些行?

[英]How to identify certain rows within a specified range of columns?

我有一個df,我需要在列表中找到任何具有值的行,這些行也位於另一個列表中。
對於此示例,我需要在以“Month”開頭的任何列中標識具有值J,Q,R的任何行。
如果列中的任何一個字母存在,則最終的df將有一個顯示true或false的列。

df = pd.DataFrame({'KEY': ['1312', '1345', '5555', '5555','5555'], 
              'Month1': [1, 1, 1,1,1],
              'Month2': [1, 1, 'J',1,1],
              'Month3': [1, 1, 1,1,1],
              'Month4': [1, 'J', 1,1,1],
              'Month5': [1, 1, 1,0,0],
              'Month6': [1, 1, 1,0,0],
              'Date1': [20120304, 20120102, 20120203,20120402,4],
              'Date2': [20120405,20120104,20120502,20120501,4],
              'StartMonth': [3,1,1,4,3],
              'EndMonth': [4,1,3,5,5],
              'ID': [1,2,3,3,4]})

df[['KEY','ID','Date1','Date2','StartMonth','EndMonth','Month1', 'Month2','Month3','Month4','Month5','Month6']]

預期結果:

    Date1       Date2       EndMonth    ID  KEY     Month1  Month2  Month3  Month4  Month5  Month6  StartMonth  HemoFacB
0   20120304    20120405    4           1   1312    1       1       1       1       1       1       3           False
1   20120102    20120104    1           2   1345    1       1       1       J       1       1       1           True
2   20120203    20120502    3           3   5555    1       J       1       1       1       1       1           True
3   20120402    20120501    5           3   5555    1       1       1       1       0       0       4           False
4   4           4           5           4   5555    1       1       1       1       0       0       3           False

我的初步嘗試導致以下錯誤:

codes = ['J','Q','R']
cols = [col for col in df if col.startswith(('Month'))]
df['HemoFacB'] = np.where(df[cols].isin(codes),1,0)

ValueError: Wrong number of items passed 6, placement implies 1

我忘了添加.any()

以下代碼有效。

df['HemoFacB'] = np.where(df[cols].isin(codes),1,0).any(1)

該錯誤表明我試圖將太多(6個cols)項目比較為1個結果。 通過使用.any() ,如果任何迭代(cols)='True',則此函數返回'True',如果iterable返回全部'False',則返回false,最終將項目數減少到1。所以通過添加.any(1)到最后,腳本合並了傳遞給1項的6項。

這是一個不使用numpy的解決方案。 我沒有使用所有的字段,但我相信你會理解它。 另外,我在操作字典后最后使用了DataFrame。 我覺得這樣做要容易得多。

import pandas as pd

mydict = {'KEY': ['1312', '1345', '5555', '5555','5555'], 'Month1': [1, 'J', 3,4,'J']}

#print(df)

truth_list = []
for val in zip(*mydict.values()):
    #print(val)
    #print("This is key: {} and value: {}".format(key, val))
    if 'J' in val:
        #print("True")
       truth_list.append('True')
    else:
        #print("False")
        truth_list.append('False')
    #print("Row {}".format(row = row + 1))

mydict.update({'HemoFacB': truth_list})

df = pd.DataFrame(mydict)
print(df)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM