简体   繁体   English

根据另一个 DF 列中值的第一位数字更改 DF 列中的值

[英]Change values in DF Column based first digit of value in another DF Column

I have the following dataframe and for my purposes, when the first digit in the Subref is X, the Centre should be X and when the fist letter of the Subref is Y, the Centre value should be Y.我有以下数据框,出于我的目的,当 Subref 中的第一个数字为 X 时,中心应为 X,当 Subref 的第一个字母为 Y 时,中心值应为 Y。

So how do I go from this df那么我如何从这个 df

 Subref     Det      Centre
0   C12345  JOHNEL      1
1    C3245    BVDI      3
2  X035769  JOHNEL      0
3  Y038450    BVDI      0

To this df对这个df

 Subref     Det      Centre
0   C12345  JOHNEL      1
1    C3245    BVDI      3
2  X035769  JOHNEL      X
3  Y038450    BVDI      Y

You can use str[0] to get the first character, then where or loc or np.where to replace您可以使用str[0]获取第一个字符,然后使用wherelocnp.where来替换

first_chars = df['Subref'].str[0]

df['Centre'] = df['Centre'].where(first_chars=='C', first_chars)

# or 
# df['Centre'] = np.where(first_char=='C', df['Center'], first_chars)

# or
# df.loc[first_chars!='C', 'Centre'] = first_chars

Output:输出:

    Subref     Det Centre
0   C12345  JOHNEL      1
1    C3245    BVDI      3
2  X035769  JOHNEL      X
3  Y038450    BVDI      Y

Try like this:像这样尝试:

df.loc[df['Subref'].str[0].isin(['X','Y']),'Centre'] = df['Subref'].str[0]
print(df)

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

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