给定条件,修改数据框的值

And*_*nte 2 python pandas

我有一个数据框,其中包含最多一个字母和三个数字的代码,例如:A478。一些代码只有一个或两个数字,但是我需要在所有具有三个数字的值之前加一个点,以将它们转换为以下形式:

A213至A21.3

简而言之,我需要以这种方式转换df:

id code1 code2 code3 code4
0  A099  B25   A022  NaN
1  B21   J2    Z23   H355
2  C212 C03  NaN   NaN
Run Code Online (Sandbox Code Playgroud)

id code1 code2 code3 code4
0  A09.9 B25   A02.2 NaN
1  B21   J2    Z23   H35.5
2  C21.2 C03  NaN   NaN
Run Code Online (Sandbox Code Playgroud)

我尝试使用类似的方法,但是语法无效,所以我不知道如何评估只有三位数字(或4个str)时才发生的情况。

df.apply(lambda x: x.str[:3]+'.'+x.str[3:] if len(x) == 4)
Run Code Online (Sandbox Code Playgroud)

Ste*_*tef 5

对于所有“代码”列,applymap如果元素不是NaN并且其长度为4,则将lambda映射到插入点的元素:

df.iloc[:,1:] = df.iloc[:,1:].applymap(lambda x: x[:3]+'.'+x[3:] if not pd.isna(x) and len(x) == 4 else x)
Run Code Online (Sandbox Code Playgroud)

结果:

   id  code1 code2  code3  code4
0   0  A09.9   B25  A02.2    NaN
1   1    B21    J2    Z23  H35.5
2   2  C21.2   C03    NaN    NaN
Run Code Online (Sandbox Code Playgroud)

PS:如果id是索引,则可以df.applymap()直接在整个数据帧上使用。