:我尝试的所有内容都替换了第一列中的键值对,但不是第一列和第二列中的值。这是代码:
module_names = {442990: 'Thank You', 442896:'Depression', 442924:'Irritability', 442879:'Anxiety', 442985:'sleep', 442875:'Meds'}
for key, value in module_names.iteritems():
df['module'].replace(key,value,inplace=True)
print df.head(15)
for key, value in module_names.iteritems():
df['inResponseTo'].replace(key,value,inplace=True)
print df.head(15)
输出:
module inResponseTo botNickname botID result \
1 Thank You 442896 Web-Ducky 36931 4
3 Depression 442924 Web-Ducky 36931 4
5 Irritability 442879 Web-Ducky 36931 3
7 Anxiety 442985 Web-Ducky 36931 4
9 sleep 442875 Web-Ducky 36931 yes
11 Meds 442875 Web-Ducky 36931 NaN
13 Meds 442864 Web-Ducky 36931 NaN
19 Thank You 442896 Ducky 36931 3
你可以看到我甚至都没有想要简洁,但我打破了它,看看我是否能发现我的错误。现在我很难过。 TIA
答案 0 :(得分:1)
IIUC如果需要通过dict
替换某些列中的值,则最简单的是删除循环:
df['inResponseTo'].replace(module_names,inplace=True)
print df
module inResponseTo botNickname botID result
1 Thank You Depression Web-Ducky 36931 4
3 Depression Irritability Web-Ducky 36931 4
5 Irritability Anxiety Web-Ducky 36931 3
7 Anxiety sleep Web-Ducky 36931 4
9 sleep Meds Web-Ducky 36931 yes
11 Meds Meds Web-Ducky 36931 NaN
13 Meds 442864 Web-Ducky 36931 NaN
19 Thank You Depression Ducky 36931 3
如果需要map
(其中不匹配get NaN
):
df['inResponseTo'] = df['inResponseTo'].map(module_names)
print (df)
module inResponseTo botNickname botID result
1 Thank You Depression Web-Ducky 36931 4
3 Depression Irritability Web-Ducky 36931 4
5 Irritability Anxiety Web-Ducky 36931 3
7 Anxiety sleep Web-Ducky 36931 4
9 sleep Meds Web-Ducky 36931 yes
11 Meds Meds Web-Ducky 36931 NaN
13 Meds NaN Web-Ducky 36931 NaN
19 Thank You Depression Ducky 36931 3
编辑:
如果需要多列中的replace
:
print (df)
module inResponseTo botNickname botID result
1 Thank You 442896 Web-Ducky 36931 442896
3 Depression 442924 Web-Ducky 36931 442924
5 Irritability 442879 Web-Ducky 36931 442879
7 Anxiety 442985 Web-Ducky 36931 442985
9 sleep 442875 Web-Ducky 36931 442875
11 Meds 442875 Web-Ducky 36931 442875
13 Meds 442864 Web-Ducky 36931 442864
19 Thank You 442896 Ducky 36931 442896
df[['inResponseTo','result']] = df[['inResponseTo','result']].replace(module_names)
print (df)
module inResponseTo botNickname botID result
1 Thank You Depression Web-Ducky 36931 Depression
3 Depression Irritability Web-Ducky 36931 Irritability
5 Irritability Anxiety Web-Ducky 36931 Anxiety
7 Anxiety sleep Web-Ducky 36931 sleep
9 sleep Meds Web-Ducky 36931 Meds
11 Meds Meds Web-Ducky 36931 Meds
13 Meds 442864 Web-Ducky 36931 442864
19 Thank You Depression Ducky 36931 Depression