簡體   English   中英

如何使用 dataframe 的 column_name 作為行上的值?

[英]How can I use the column_name of a dataframe as a value on the rows?

我有這個框架,2 列(藍色和紅色)和值(0,1)

**Blue   Red**
   0      1
   1      1

我想要一個 Dataframe 結果,如果列 Red 的值=1,用 name_column Red 替換這個 1

**Blue   Red**
   0    Red
 Blue   Red

我可以用“for”來做到這一點,但是,你知道另一種方法嗎? 謝謝

一種方法是將df和相同形狀的數組相乘:

df * np.broadcast_to(df.columns.values, df.shape)

   Blue  Red
0        Red
1  Blue  Red

這使您最終在所有單元格中都有字符串。


另一種解決方案是對每列使用where

df.apply(lambda s: s.where(s.eq(0), s.name))

這使您最終得到混合類型。


作為一般經驗法則,最好為每列使用單一類型的 arrays。

使用apply function 效率更高。 我正在使用astype(object)所以我可以使用replace function:

import pandas as pd
df = pd.DataFrame([[0, 1], [1, 0]], columns=['**Blue', 'Red**'])

df = df.apply(lambda x: x.astype(object).replace(1, x.name.replace("**", '')))
print(df)

使用np.where

df1 = pd.DataFrame(np.where(df.eq(1), df.columns, df), columns=df.columns)

打印(df1)

   Blue  Red
0     0  Red
1  Blue  Red

您可以調用此 function,也許它可能對您有所幫助:

def func(val):
    if (val==1):
        return "red"
    else:
        return 'Blue'
val=int(input())
print(func(val))

暫無
暫無

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

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