[英]Iterate through dataframe rows and replace elements of strings within a specific column
I have some tables from the Bureau of Labor Statistics that I converted to cvs files in Python.我有一些来自劳工统计局的表格,我将它们转换为 Python 中的 cvs 文件。 The 'Item' column has some rows with multiple '.'.
“项目”列有一些带有多个“。”的行。 I'm trying to iterate through these rows and replace these '.'
我正在尝试遍历这些行并替换这些“。” with ''.
和 ''。
I've tried:我试过了:
for row in age_df_1989['Item']:
if '.' in row:
age_df_1989['Item'].replace('.','')
Any ideas on what I can do for this?关于我可以为此做些什么的任何想法?
No assigning age_df_1989['Item'].replace('.','')
to a variable won't change the original data, you need to do this:没有将
age_df_1989['Item'].replace('.','')
分配给变量不会更改原始数据,您需要这样做:
for row in age_df_1989['Item']:
if '.' in row:
row['Item'] = row['Item'].replace('.','')
Try apply
尝试
apply
age_df_1989['Item'] = age_df_1989['Item'].apply(lambda x: x.replace('.', '')
Simple & faster than a for loop比 for 循环更简单、更快
Use the vectorised str method replace : This is much faster than the iterrows or for loop or apply option.使用矢量化 str 方法replace :这比 iterrows 或 for 循环或应用选项快得多。
You can do something as simple as你可以做一些简单的事情
df['column name'] = df['column name'].str.replace('old value','new value')
For your example, do this:对于您的示例,请执行以下操作:
age_df_1989['Item'] = age_df_1989['Item'].str.replace('.', '')
Here's an example output of this:这是一个示例 output :
c = ['Name','Item']
d = [['Bob','Good. Bad. Ugly.'],
['April','Today. Tomorrow'],
['Amy','Grape. Peach. Banana.'],
['Linda','Pink. Red. Yellow.']]
import pandas as pd
age_df_1989 = pd.DataFrame(d, columns = c)
print (age_df_1989)
age_df_1989['Item'] = age_df_1989['Item'].str.replace('.', '')
print (age_df_1989)
Dataframe: age_df_1989: Original Dataframe:age_df_1989:原创
Name Item
0 Bob Good. Bad. Ugly.
1 April Today. Tomorrow
2 Amy Grape. Peach. Banana.
3 Linda Pink. Red. Yellow.
Dataframe: age_df_1989: After the replace command Dataframe:age_df_1989:替换命令后
Name Item
0 Bob Good Bad Ugly
1 April Today Tomorrow
2 Amy Grape Peach Banana
3 Linda Pink Red Yellow
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.