简体   繁体   English

根据列值组合行和列名(python)

[英]Combine row and column name based on column value (python)

在此处输入图片说明

If I have above table, I would like to combine rowname + columnname if column value = 'Y'.如果我有上表,如果列值 = 'Y',我想组合行名 + 列名。 How would I do it?我该怎么做?

The end result should be a list: a = (10,11,2290,20,21)最终结果应该是一个列表:a = (10,11,2290,20,21)

I tried the following:我尝试了以下方法:

Create a new column:创建一个新列:

df['haves'] = df.eq('Y').dot(df.columns + ', ').str.rstrip(', ')

col= df[["haves"]]
row= df[["PromofactsID"]]

row_lol = row.values.tolist()
col_lol = col.values.tolist()

Then I want to combine row_lol and col_lol but the haves column becomes one string and not individual elements.然后我想组合 row_lol 和 col_lol 但 hass 列成为一个字符串而不是单个元素。

Pls advise, Thanks in advance!请指教,提前致谢!

Regards.问候。

I tried to do it like this:我试着这样做:

Here's what should work for you:以下是适合您的方法:

final_list = list()
for index, row in df.iterrows():
    for (columnName, columnData) in row[1:].iteritems():
        if columnData == 'Y':
            final_list.append(row['ID']*10+int(columnName))

Input dataframe输入数据框

    ID  0   1
0   1   Y   Y
1   229 Y   None
2   2   Y   Y

Output list输出列表

[10, 11, 2290, 20, 21]

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

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