python 变量名重新赋值 变量重新赋值 通过字典的方式

对数据表的操作经常需要重命名变量,或者中心赋值某个变量,可以使用numpy的where,也可以使用rename, 或者使用replace。

使用字典的方式比较方便。下面是代码:

import pandas as pd
import statsmodels.api as sm
import numpy as np
df = pd.read_excel("sn_short_for_reg.xlsx")

df.keys()
df['y_sat']

df_new = df[df['y_sat'].isnull() == False]

df_new.shape

y_sat = df_new['y_sat']
y_sat

y2 = np.where(y_sat >0, 1, 0)

y2
pd.Series(y2).value_counts()

df_new['y2'] = y2

df
df_new

df_new_short = df_new[df_new['sat_default_idx'] == 0]

df_new_short.shape

df_new_short
df_new_short

x3 = df_new_short['x3_post_level']
x3.value_counts()

d_x3 = {
    "市":2,
    "省":1,
    "区":3,
    "天津市":1,
    "北京市":1,
    "自治州":2,
    "县":3,
    "盟":2,
    "重庆市":1,
    "上海市":1
}

df_new_short['x3_post_level'].replace(d_x3)
df_new_short['x3_post_level']

df_new_short['x3_2'] =df_new_short['x3_post_level'].replace(d_x3)

df_new_short.head()

df_new_short.keys()
df_new_short['x1_psot_length']

d_newname = {
    "x1_psot_length":"x1_post_length"
}

df_new_short.rename(columns=d_newname)

数据表概览

使用where赋值

 

使用字典 对变量重新赋值

结果如下:

使用字典重命名 变量,要使用inplace选项,不然数据表不会改

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值