简体   繁体   English

根据每行中的值获取列标题

[英]Get column header based on a value in each row

I have a pandas dataframe, something like below (just an illustration): 我有一个pandas数据帧,如下所示(只是一个插图):

import datetime
todays_date = datetime.datetime.now().date()   
index = pd.date_range(todays_date-datetime.timedelta(10), periods=2, freq='D')
columnheader=['US', 'Canada', 'UK', 'Japan']
data=np.array([[3,4,2,1],[1,4,3,2]])
df = pd.DataFrame(data, index=index, columns=columnheader)

Which results in: 结果如下:

            US  Canada  UK  Japan
2015-07-26   3       4   2      1
2015-07-27   1       4   3      2

I need to find the column header whose value is 1 and 2 for each row. 我需要找到每个行的值为1和2的列标题。

so I should get 所以我应该得到

['Japan', 'UK']
['US', 'Japan']

You can do the following, this tests each row for membership of 1,2 using isin and if so this generates a boolean series, you can use this to index into the columns by calling apply again, we convert this to a list because the dimensions won't align if you don't do this: 您可以执行以下操作,使用isin测试每一行的成员资格1,2如果是这样生成一个布尔系列,您可以通过再次调用apply来使用它来索引列,我们将其转换为列表,因为维度如果你不这样做,将不会对齐:

In [191]:
df.apply(lambda x: x.isin([1,2]), axis=1).apply(lambda x: list(df.columns[x]), axis=1)

Out[191]:
2015-07-26    [UK, Japan]
2015-07-27    [US, Japan]
Freq: D, dtype: object

output from inner apply : 内部输出apply

In [192]:
df.apply(lambda x: x.isin([1,2]), axis=1)

Out[192]:
               US Canada     UK Japan
2015-07-26  False  False   True  True
2015-07-27   True  False  False  True

EDIT 编辑

If you want to maintain order then you can define a func to test each value and return this as a series: 如果您想维护订单,那么您可以定义一个func来测试每个值并将其作为一个系列返回:

In [209]:
filter_vals=[1,2]
def func(x):
    l=[]
    for val in filter_vals:
        for col in df:
            if x[col] == val:
                l.append(col)
​
    return pd.Series(l)
df.apply(func, axis=1)

Out[209]:
                0      1
2015-07-26  Japan     UK
2015-07-27     US  Japan

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

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