[英]How do I create a new column based on matching values in two different dataframes?
[英]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
我想得到以下內容,不太確定如何根據最后 3 位數字拆分為 col3 以及前面的任何內容為 col1
col2 col3
0 25 021
1 25 002
2 8 002
3 40 211
4 2 232
5
這是我的方法:
df['col2'] = df['col1'].astype(str).str[-3:]
df['col1'] = df['col1'].astype(str).str[:-3]
Output:
col1 col2
0 25 021
1 25 002
2 8 002
3 40 211
4 2 232
嘗試這個。
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)
只是對 Pandas 的字符串拆分方法的一種嘗試; 您可以包裝分隔符(在正則表達式中),以便它包含在 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.