简体   繁体   English

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

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

I have my data as我有我的数据

Age年龄 Gender性别
2 Year(s) 2年) Male男性
3 Month(s) 3个月) Male男性
2 Day (s) 2天) Female女性

And I want to make it to我想做到

Age年龄 Gender性别
2 2 Male男性
Below 1 year 1年以下 Male男性
Below 1 year 1年以下 Female女性

Use the replace function.使用替换function。 In your case:在你的情况下:

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

Figured it out, I did this, I copy pasted the actual code from my code editor想通了,我做到了,我从代码编辑器中复制粘贴了实际代码

#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.

相关问题 如何使用Python将特定的数组值保存到Excel中的单元格? - How do I save a specific array value to a cell in Excel with Python? 如何用数字替换熊猫数据框中的单词? - How can I replace words in a panda data frame with a number? 在带有python的excel中,如何在包含多个单词的单元格中从整个列中查找单词? - In excel with python, how do you find words, from an entire column, in a cell containing multiple words? 如果某个单元格的python包含“ 0”,是否可以删除Excel中的行? - Is there a way to remove a row in excel if a certain cell contains a “0” with python? 如何根据单元格值是否包含某个字符来遍历 excel 工作表 - How to iterate through an excel sheet based on whether the cell value contains a certain character 熊猫包含带有替换的公式 - Panda contains formula with replace 如何修改包含列表的 pandas dataframe 单元格的值? - How do I modify the value of a pandas dataframe cell that contains a list in it? 如何用 Python 中的列表中的项目替换字符串中的单词 - How Do I Replace Words In a String With Items In a List In Python 如何检查单元格值是否仅包含“空格”? - How do I check if the cell value contains only "space"? 如何根据条件替换 Panda 数据框列中的单元格 - How do I replace cells in a Panda dataframe column based on a condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM