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

时间:2020-10-29 14:30:26

标签: python pandas

我有以下数据框,出于我的目的,当Subref的第一位数字为X时,Center应该为X,而Subref的首字母为Y时,Center值应该为Y。

那我要如何从这个df中去

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

到此df

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

2 个答案:

答案 0 :(得分:1)

您可以使用net.sf.saxon.trans.LicenseException HResult=0x80131500 Message=Requested feature (schema-aware XSLT) requires Saxon-EE. You are using Saxon-EE software, but the Configuration is an instance of net.sf.saxon.Configuration; to use this feature you need to create an instance of com.saxonica.config.EnterpriseConfiguration Source=saxon9ee StackTrace: at net.sf.saxon.Configuration.checkLicensedFeature(Int32 feature, String name, Int32 localLicenseId) at net.sf.saxon.PreparedStylesheet..ctor(Compilation compilation) at net.sf.saxon.style.StylesheetModule.loadStylesheet(Source styleSource, Compilation compilation) at net.sf.saxon.style.Compilation.compileSingletonPackage(Configuration config, CompilerInfo compilerInfo, Source source) at net.sf.saxon.s9api.XsltCompiler.compile(Source source) at Saxon.Api.XsltCompiler.Compile(Stream input) at ValidateXslt.Program.Main(String[] args) in C:\Users\m_r_n\source\repos\SaxonEEExample\ValidateXslt\Program.cs:line 33 获取第一个字符,然后使用str[0]whereloc替换

np.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

答案 1 :(得分:0)

尝试这样:

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