繁体   English   中英

如何替换包含 Python Panda 中某些单词的单元格中的值,就像在 Excel 中一样?

[英]How do I replace the value in a cell that contains certain words in Python Panda like in Excel?

我有我的数据

年龄 性别
2年) 男性
3个月) 男性
2天) 女性

我想做到

年龄 性别
2 男性
1年以下 男性
1年以下 女性

使用替换function。 在你的情况下:

df.Age.replace({
    "2 Year(s)": "2",
    "3 Month(s)": "Below 1 year",
    ...
    },
    inplace=True
)

想通了,我做到了,我从代码编辑器中复制粘贴了实际代码

#split Patient Age and append back to master list
alldata[['Age', 'Unit']] = alldata['Patient Age'].str.split(' ', expand=True)

#Separate into subdata of Years, Months, Days and Hours
dfunit = alldata.groupby(['Unit'])
dfyears = dfunit.get_group('Year(s)')
dfmonths = dfunit.get_group('Month(s)')
dfdays = dfunit.get_group('Day(s)')
dfhours = dfunit.get_group('Hour(s)')


#Replace value of Mpnths, Days and Hours with 0
dfmonths['Age'] = dfmonths['Age'].str.replace('\d', '0')
dfdays['Age'] = dfdays['Age'].str.replace('\d', '0')
dfhours['Age'] = dfhours['Age'].str.replace('\d', '0')


#Combine sublist back to master list
newdata = dfyears.append(dfmonths).append(dfdays).append(dfhours)

#Convert value in Age to int
newdata['Age'] = newdata['Age'].astype(int)
newdata['Age'].dtypes

#Separate Age into Age Group
bins = [0, 20, 30, 40, 50, 60, 70, 120]
labels = ['0-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70+']
newdata['Agerange'] = pd.cut(newdata['Age'], bins, labels = labels,include_lowest = True)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM