【问题标题】:modifying columns of pandas data-frame on different conditions在不同条件下修改熊猫数据框的列
【发布时间】:2017-11-15 10:01:56
【问题描述】:
这是我的数据框,我想将 c 和 d 列中的值转换为 KB。
这里 M 代表兆字节,G 代表千兆字节。如何做到这一点。
b c d
abc 12.8G 12.6G
def 2.67M 3.4G
ghi 12.5G 34.5M
jkl 12.1G 1.2G
【问题讨论】:
标签:
python-3.x
pandas
dataframe
【解决方案1】:
使用.str 访问器的字典映射将有所帮助,即
di = {'M':10**3,'G':10**6 }
df[['c','d']] = df[['c','d']].apply(lambda x : pd.to_numeric(x.str[:-1]) * x.str[-1].map(di)).astype(str) + 'KB'
b c d
0 abc 12800000.0KB 12600000.0KB
1 定义 2670.0KB 3400000.0KB
2 吉 12500000.0KB 34500.0KB
3 jkl 12100000.0KB 1200000.0KB
如果您只需要整数,请使用
df[['c','d']].apply(lambda x : pd.to_numeric(x.str[:-1]) * x.str[-1].map(di)).astype(int)