Pandas: 如何编辑列中的值
Pandas: How to edit values in a column
我有一个带有一列值前缀的 df:{H、HR、S 等}。我想编辑这些值,使其 returns h
用于所有 H, HR, HJ, HC
和 s
用于所有 S, SR, SJ SC
。数据为here
session prefix number disposition catcode bill
0 114 H 131 support J6200 H131
1 114 H 138 oppose L1100 H138
2 114 H 140 support NaN H140
3 114 H 140 oppose J7500 H140
4 114 H 140 support NaN H140
我 运行 来自 MaxU 的以下内容:
df.replace({'prefix': {r'^(H|HR|HC|HJ|)$': 'h', r'^(S|SR|SC|SJ|)$ ': 's'}}, regex=True, inplace=True)
而且有效!问题已解决!
session prefix number disposition catcode
0 114 h 131 support J6200
1 114 h 138 oppose L1100
2 114 h 140 support NaN
试试这个:
df.replace({'prefix': {r'^(H|HR|H\*)$': 'h', r'^(S|SR|S\*)$': 's'}}, regex=True, inplace=True)
如果您只想拥有前缀列的第一个字母:
df.prefix.str[0]
所以要用小写的第一个字母替换它:
df.prefix = df['prefix'].str[0].str.lower()
我有一个带有一列值前缀的 df:{H、HR、S 等}。我想编辑这些值,使其 returns h
用于所有 H, HR, HJ, HC
和 s
用于所有 S, SR, SJ SC
。数据为here
session prefix number disposition catcode bill
0 114 H 131 support J6200 H131
1 114 H 138 oppose L1100 H138
2 114 H 140 support NaN H140
3 114 H 140 oppose J7500 H140
4 114 H 140 support NaN H140
我 运行 来自 MaxU 的以下内容:
df.replace({'prefix': {r'^(H|HR|HC|HJ|)$': 'h', r'^(S|SR|SC|SJ|)$ ': 's'}}, regex=True, inplace=True)
而且有效!问题已解决!
session prefix number disposition catcode
0 114 h 131 support J6200
1 114 h 138 oppose L1100
2 114 h 140 support NaN
试试这个:
df.replace({'prefix': {r'^(H|HR|H\*)$': 'h', r'^(S|SR|S\*)$': 's'}}, regex=True, inplace=True)
如果您只想拥有前缀列的第一个字母:
df.prefix.str[0]
所以要用小写的第一个字母替换它:
df.prefix = df['prefix'].str[0].str.lower()