DataFrame有条件地合并列

时间:2019-11-28 02:37:18

标签: python pandas

我有一个28列的DataFrame。我想有条件地将两列合并在一起以创建一个新列,当我处理数据并引入其他数据集时,这将成为我的关键。我将不得不在每个数据集中再次创建密钥。

我想将“ CN”和“ ON”列连接在一起。有时“ ON”为空白或仅有一个空格,因此我需要先对其进行修剪。从逻辑上讲,我正在尝试执行以下操作。

如果Trim('ON')为空白,则'CN ON'='CN'ELSE'CN ON'='CN'+'-'+'ON'

DataFrame

   CN  ON    POC
0  W1      Name1
1  Z2      Name3
2  B3  YY  Name1
3  W1  A2  Name4

import pandas as pd
df = pd.DataFrame({'CN': ['W1', 'Z2', 'B3', 'W1'],
                   'ON': ['', ' ', 'YY', 'A2'],
                   'POC': ['Name1', 'Name3', 'Name1', 'Name4']
                   })

所需结果

   CN ON  CN  ON    POC
0     W1  W1      Name1
1     Z2  Z2      Name3
2  B3-YY  B3  YY  Name1
3  W1-A2  W1  A2  Name4

import pandas as pd
df = pd.DataFrame({'CN ON': ['W1','Z2','B3-YY','W1-A2'],
                   'CN': ['W1', 'Z2', 'B3', 'W1'],
                   'ON': ['', ' ', 'YY', 'A2'],
                   'POC': ['Name1', 'Name3', 'Name1', 'Name4']
                   })       

我发现了一些类似的问题和答案,但是我无法完全起作用。

这是我到目前为止所拥有的。我在弄清楚如何修剪和检查该字段是否为空白时遇到了麻烦。它目前无法正常工作,我感觉好像撞墙了。

import numpy as np
df['CN ON'] = df.apply(lambda r: (r['CN'] if np.where(df['ON'].applyman(lambda x: x == '')) else r['CN'] + '-' + r['ON'])

任何指导或协助将不胜感激!

3 个答案:

答案 0 :(得分:2)

使用str.catmask

df.CN.str.cat(df.ON, '-').mask(df.ON.str.strip().eq(''), df.CN)

Out[903]:
0       W1
1       Z2
2    B3-YY
3    W1-A2
Name: CN, dtype: object

如果要将其插入到df的开头,请使用insert,位置为0

s = df.CN.str.cat(df.ON, '-').mask(df.ON.str.strip().eq(''), df.CN)
df.insert(0, 'CN ON', s)

print(df)

Out[906]:
   CN ON  CN  ON    POC
0     W1  W1      Name1
1     Z2  Z2      Name3
2  B3-YY  B3  YY  Name1
3  W1-A2  W1  A2  Name4

注意:df.insertinplace的操作,因此您不需要分配回去。它直接修改df

答案 1 :(得分:2)

我将进行字符串求和

protected void Reg(object sender, EventArgs e)
{
    string em = email.Value;
    string id = nationalid.Value;
    string pass = password.Value;
    string country = DDLcountry.SelectedItem.Text;
    string dateof = dob.Value;

    string cid = ((id.Length > 9) ? id.Substring(id.Length - 9, 9) : id);
    string uid = DDLcountry.SelectedItem.Value + cid;

    string strpass = encryptpass(pass);
    SqlCommand chk = new SqlCommand("SELECT * FROM UserData WHERE ([email] = @email)", con);
    chk.Parameters.AddWithValue("@email", em);
    con.Open();
    SqlDataReader reader = chk.ExecuteReader();
    if (!reader.HasRows)
    {
        Random rand = new Random();
        code = rand.Next(100001, 999999).ToString();
        sendCode();
        SqlCommand cmd = new SqlCommand("insert into UserData(userID, email, country, nationalID, password, activatecode, DOB)values(@userID, @email, @country, @nationalID, @password, @code, @DOB)", con);
        cmd.Parameters.AddWithValue("@userID", uid);
        cmd.Parameters.AddWithValue("@email", em);
        cmd.Parameters.AddWithValue("@country", country);
        cmd.Parameters.AddWithValue("@nationalID", id);
        cmd.Parameters.AddWithValue("@password", strpass);
        cmd.Parameters.AddWithValue("@code", code);
        cmd.Parameters.AddWithValue("@DOB", dateof);
        int j = cmd.ExecuteNonQuery();
        if (j != 0)
        {
            Response.Redirect("ActivationEmail.aspx?em=" + email.Value);
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Registration Failed !! Try again !!')", true);
        }
    }
    else
    {
        //user existed
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Email Existed !! Try again !!')", true);
    }
    con.Close();
}

答案 2 :(得分:1)

In [242]: df
Out[242]:
   CN  ON    POC
0  W1      Name1
1  Z2      Name3
2  B3  YY  Name1
3  W1  A2  Name4

In [243]: df['CN-ON'] = df.apply(lambda x: '{}{}'.format(x['CN'], '-' + x['ON'] if x['ON'].strip() else ''), axis=1)

In [244]: df
Out[244]:
   CN  ON    POC  CN-ON
0  W1      Name1     W1
1  Z2      Name3     Z2
2  B3  YY  Name1  B3-YY
3  W1  A2  Name4  W1-A2
相关问题