如何将DataFrame中一列的数值的最后三位拆分成两个新的DataFrame?

3
df=pd.DataFrame({'col1':[25021,25002,8002,40211,2232,""]})

    col1    
0   25021    
1   25002
2   8002
3   40211
4   2232
5   

我想要获得以下内容,但不确定如何根据最后三位数字分割为col3以及前面的内容分割到col1。
    col2   col3    
0   25     021       
1   25     002       
2   8      002      
3   40     211       
4   2      232 
5
3个回答

3
这是我的方法:
df['col2'] = df['col1'].astype(str).str[-3:]

df['col1'] = df['col1'].astype(str).str[:-3]

输出:

   col1 col2
0    25  021
1    25  002
2     8  002
3    40  211
4     2  232

0

试试这个。

df=pd.DataFrame({'col1':[25021,25002,8002,40211,2232]})
df['col2'] = df['col1'].astype(str).apply(lambda x:x[-3:]).astype(int)
df['col1'] = df['col1'].astype(str).apply(lambda x:x[:-3]).astype(int)

0
只是玩弄Pandas的string split方法; 您可以将分隔符(在正则表达式中)包装起来,使其包含在输出中:
(df
 .astype(str)
 .col1
 .str.split(r'(\d{3}$)', n=1, expand=True)
 .drop(2,axis=1)
 .set_axis(['col1','col2'],axis='columns')
)

    col1    col2
0    25     021
1    25     002
2    8      002
3    40     211
4    2      232

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接