简体   繁体   English

如何将 Dataframe 列中值的最后 3 位拆分为两个新的数据帧?

[英]How do I split last 3 digits in values in a column in a Dataframe into two new Dataframes?

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

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

I would like to get the following, not too sure how to split based on last 3 digits into col3 and whatever preceding into col1我想得到以下内容,不太确定如何根据最后 3 位数字拆分为 col3 以及前面的任何内容为 col1

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

This is my approach:这是我的方法:

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

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

Output: Output:

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

Try this.尝试这个。

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)

Just a play on Pandas' string split method;只是对 Pandas 的字符串拆分方法的一种尝试; you can wrap the delimiter(in a regex), so that it is included in the output:您可以包装分隔符(在正则表达式中),以便它包含在 output 中:

(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

暂无
暂无

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

相关问题 如何根据两个不同数据框中的匹配值创建新列? - How do I create a new column based on matching values in two different dataframes? 如何在 pandas dataframe 中插入重复的列,并从新列的值中删除最后 3 个数字? - How do I insert a duplicated column in a pandas dataframe with the last 3 numbers removed from the values of the new column? 如何将 dataframe 拆分为两个数据帧 - How to split a dataframe into two dataframes 如何将两个 pandas 数据帧与它们在列中的值对齐? - How do I align two pandas dataframes on their values in a column? 如何根据column1的值将1个数据帧拆分为两个数据帧 - How to split 1 dataframe into two dataframes based on column1's value 将数据框中的列拆分为两个新数据帧 - Split columns in dataframe into two new dataframes 如何通过列值的范围将单个数据帧拆分为多个数据帧? - How do I split a single dataframe into multiple dataframes by the range of a column value? 如何将 Dataframe 列一分为二,但考虑到有时没有什么可拆分的并且该值属于第二列? - How do I split a Dataframe column in two but taking into account that sometimes there is nothing to split and the value belongs to the second column? 使用pandas,如何比较两个数据帧中2列之间的值并将它们推送到新的数据帧? - Using pandas, how can I compare the values between 2 columns from two dataframes and push them to a new dataframe? 如何创建一个新的 dataframe 包含比较其他两个数据帧的差异值? - How can I create a new dataframe that contains the difference values from comparing two other dataframes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM