为数据框中的行值分配数字

时间:2018-09-21 10:13:49

标签: python pandas loops

让我说我有一个数据框

A     B     C
john  I     agree 
ryan  II    agree
rose  V     strongly agree 
Shawn VI    disagree 

我要做的是像这样为C列值分配数字?

A     B     C
john  I     1 
ryan  II    1
rose  V     2
Shawn VI    0

有人知道该怎么做吗?

2 个答案:

答案 0 :(得分:3)

dictionary使用map

df['C'] = df['C'].map({'agree':1, 'strongly agree':2, 'disagree':0})
print (df)
       A   B  C
0   john   I  1
1   ryan  II  1
2   rose   V  2
3  Shawn  VI  0

答案 1 :(得分:0)

您也可以使用const WebSocket = require('ws'); const http = require('http'); const server = http.createServer(); const wss = new WebSocket.Server({noServer: true}); wss.on('connection', (ws, req) => { console.log('Opened Connection with URL ' + req.url.substr(1)); ws.on('close', () => { console.log('Closed Connection with URL ' + req.url.substr(1)); }); }); server.on('upgrade', (request, socket, head) => { if (request.headers['sec-websocket-protocol'] === 'appProtocol') { wss.handleUpgrade(request, socket, head, (ws) => { wss.emit('connection', ws, request); }) } else { socket.destroy(); } }); server.listen(3300); apply

lambda

只需

        A               C
0  john           agree
1  ryan  strongly agree
2  rose        disagree

结果

df_t['C'] = df_t['C'].apply(lambda x: 1 if x =='agree' else (0 if x=='disagree' else 2))

但是使用@jezrael上面指出的 A C 0 john 1 1 ryan 2 2 rose 0 是最佳解决方案。