我有一個這樣的資料框:
| 代碼 |
|---|
| DA |
| D B |
| 直流電 |
| DD |
| 德 |
| DF |
| 總署 |
| DX |
| DY |
| 大區 |
我想在上表中添加一列,以便代碼列中的每個值都有一個固定值,如下表所示:
| 代碼 | 價值 |
|---|---|
| DA | 一種 |
| D B | 一種 |
| 直流電 | 一種 |
| DD | 乙 |
| 德 | 乙 |
| DF | 乙 |
| 總署 | C |
| DX | C |
| DY | C |
我該怎么做??
uj5u.com熱心網友回復:
嘗試這個:
Value = ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
df['Value'] = Value
uj5u.com熱心網友回復:
df = pd.DataFrame( {'Code': ['DA', 'DB', 'DC', 'DD', 'DE', 'DF', 'DG', 'DX', 'DY']} )
dct = {'DA': 'A', 'DB': 'A', 'DC': 'A',
'DD': 'B', 'DE': 'B', 'DF': 'B',
'DG': 'C', 'DX': 'C', 'DY': 'C'}
df['Value'] = df['Code'].replace(dct)
print(df)
印刷:
Code Value
0 DA A
1 DB A
2 DC A
3 DD B
4 DE B
5 DF B
6 DG C
7 DX C
8 DY C
具有特定模式的示例:
df['Value'] = df['Code'].apply(lambda s: chr((int(ord(s[-1])) - 65) // 3 65))
print(df)
印刷:
0 DA A # matches the desired result
1 DB A # matches the desired result
2 DC A # matches the desired result
3 DD B # matches the desired result
4 DE B # matches the desired result
5 DF B # matches the desired result
6 DG C # matches the desired result
7 DX H # no match
8 DY I # no match
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/352454.html
