简体   繁体   English

如何在 Pandas 数据框中的列上应用格式

[英]How to apply format on Columns in Pandas dataframe

I have a pandas data frame with 90 columns and I want to apply a format to each column.我有一个包含 90 列的 Pandas 数据框,我想对每一列应用一种格式。 Each column has its own format and the function with the format has the same name as the name of the column.每列都有自己的格式,具有格式的函数与列的名称具有相同的名称。 I want to apply the format to each column on the data frame.我想将格式应用于数据框上的每一列。

For example, let's say dv, dw are two columns of my dataframe df:例如,假设 dv, dw 是我的数据框 df 的两列:

dv 
1
2
1
1
5
5

dw
2
2
1
3
2
3

def dv(dv):      
    if dv==1:
       return 1
    else:
       return 0

def dw(dw):
    if dw==2:
       return 1
    else:
       return 0

I am using the command below :我正在使用以下命令:

df['dv']=df['dv'].apply(dv)

df['dw']=df['dw'].apply(dw)

output :输出 :

dv 
1
0
1
1
0
0


dw
1
1
0
0
1
0

Problem statement: I don't want to write a .apply method for every column since I have 90 columns and want to reduce lines of code.问题陈述:我不想为每一列编写一个 .apply 方法,因为我有 90 列并且想要减少代码行数。

You can use a dictionary with the names of the columns you want to modify along with their corresponding condition and values to do the replacements.您可以使用带有要修改的列的名称及其相应条件和值的字典来进行替换。 Then, use the apply function to replace the values according to the dictionary like this:然后,使用 apply 函数根据字典替换值,如下所示:

data = [
    [1, 2],
    [2, 2],
    [1, 1],
    [1, 3],
    [5, 2],
    [5, 3]
]

df = pd.DataFrame(data, columns = ["dv", "dw"])

dict_ = {
    "dv": {
        "condition": 1,
        "x": 1,
        "y": 0
    },
    "dw": {
        "condition": 2,
        "x": 1,
        "y": 0
    }
}

def func(x):
    column = x.name
    
    return np.where(x == dict_[column]["condition"], dict_[column]["x"], dict_[column]["y"])

df[dict_.keys()].apply(func)

Example:例子:

Input:输入:

   dv  dw
0   1   2
1   2   2
2   1   1
3   1   3
4   5   2
5   5   3

Output:输出:

   dv  dw
0   1   1
1   0   1
2   1   0
3   1   0
4   0   1
5   0   0

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

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