简体   繁体   English

Python pandas 如果行包含字符串添加到表

[英]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.我的目标是打印出哪个“hmi”控制哪个“az”,在其对应的列中用“x”表示。 Example based on the above spreadsheet:基于上述电子表格的示例:

  • HMI1 controls AZ1 HMI1 控制 AZ1
  • HMI2 controls AZ2 HMI2控制AZ2
  • HMI3 controls AZ3 HMI3控制AZ3
  • HMI4 controls AZ3 HMI4控制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):我可以使用并排序到输出excel表的想法输出是(其中“X”是相应的数字):

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:我用 pd.read_excel 导入了电子表格,我的想法是使用以下代码对其进行格式化,但是我认为我很接近但走错了路:

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

Given df,给定 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.首先遍历行,感谢列,如果找到x ,则打印行和列。

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.另一种方法是基于stack()方法,然后通过列表理解访问索引。 Given above dataframe df :鉴于以上数据帧df

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

Solution is fast and very compact.解决方案快速且非常紧凑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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