![](/img/trans.png)
[英]How to create a new column based on string match of existing column in pandas
[英]Pandas: Create new column based on existing, return existing if conditionals don't match
我有一個數據集,其中包含一個具有分類值的列。 我需要對列進行標准化,因為某些值的編碼不正確。 例如,“1.0”和“3.0”應分別為“01”和“03”。 但是,當值正確時,我只需要返回我正在清理的列的值。 我想將清理后的數據包含在一個新列中。
我對 Python 和 Pandas 比較陌生。 我通常在 R 中工作。我嘗試了在 Stack 上找到的各種技術,但是在嘗試從原始列返回值是否正確時,我一直遇到問題。
任何幫助將不勝感激! 以下是一些示例數據:
import pandas as pd
d = {'col1':['01','03','1.0','10.0','7.0','3.0']}
df = pd.DataFrame(data=d)
這返回....
col1
0 01
1 03
2 1.0
3 10.0
4 7.0
5 3.0
而我希望得到...
col1 col2
0 01 01
1 03 03
2 1.0 01
3 10.0 10
4 7.0 07
5 3.0 03
您可以將數字列轉換為浮點數,然后轉換為 int,最后添加前導零。
df['col2'] = (df['col1']
.astype(float).astype(int)
.apply('{:0>2}'.format))
df['col3'] = (df['col1']
.astype(float).astype(int).astype(str)
.str.zfill(2))
print(df)
col1 col2 col3
0 01 01 01
1 03 03 03
2 1.0 01 01
3 10.0 10 10
4 7.0 07 07
5 3.0 03 03
這是您單獨設置每一列的樣式的樣式格式方法。
代碼:
df['col2'] = df['col1']
df = df.astype(float)
df = df.style.format({'col1': "{:.1f}",'col2': "{:,.0f}"})
df
輸出:
col1 col2
0 1.0 1
1 3.0 3
2 1.0 1
3 10.0 10
4 7.0 7
5 3.0 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.