简体   繁体   中英

Python pandas if row contains string add to table

I have a spreadsheet that looks as follows:

在此处输入图片说明

my goal is to print out which "hmi" controls which "az", which is indicated by an "x" in its corresponding column. Example based on the above spreadsheet:

  • HMI1 controls AZ1
  • HMI2 controls AZ2
  • HMI3 controls AZ3
  • HMI4 controls AZ3

etc..

My idea output that i can work with and sort to an output excel sheet would be(where "X" is the corresponding number):

HMIX | AZX

ive imported the spreadsheet with pd.read_excel and my thought was using the following code to format it, however i think im close but on the wrong path:

    for index, row in dfConfig.iterrows():
        if row["az1"] != "NaN":
            print(row["hmi_number"])

Given df,

df = pd.DataFrame({'hmi_number':np.arange(1,10),
                  'az1':['x']+[np.nan]*8,
                  'az2':[np.nan]+['x']+[np.nan]*7,
                  'az3':[np.nan]*2+['x']*2+[np.nan]*5,
                  'az4':[np.nan]*4+['x']*2+[np.nan]*3,
                  'az5':[np.nan]*6+['x']*2+[np.nan],
                  'az6':[np.nan]*8+['x']})

Try this:

for hmi, az in (df.set_index('hmi_number')=='x').dot(df.columns[1:]).iteritems():
    print(f'HMI{hmi} controls {az}')

Output:

HMI1 controls az1
HMI2 controls az2
HMI3 controls az3
HMI4 controls az3
HMI5 controls az4
HMI6 controls az4
HMI7 controls az5
HMI8 controls az5
HMI9 controls az6

Iterate over rows first, thank over columns, if you find the x , print the row and the columns.

for i, row in dfConfig.iterrows():
    for col in dfConfig:
        if row[col] == 'x':
            print(f'HMI{row["hmi_number"]} controls {col}')

If your looking for something that checks if something is a string try this

>>> currentColumn = "x"
>>> isinstance(currentColumn, str)
True
>>> isinstance(currentColumn, int)
False
>>> 

Another approach is based on stack() method and then accessing index by list comprehension. Given above dataframe df :

[print(f"HMI{x} controls {y}") for x,y in df.set_index("hmi_number").stack().index]

Solution is fast and very compact.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM