首页 > 解决方案 > 如何循环并用列中的特定值替换下一行的值

问题描述

我正在使用脚本重新格式化 excel 文件,这是我正在使用的数据集

   Month Amount Location
0  Month $$$    LocationA
1  Month $$$    str
2  Month $$$    str
3  Month $$$    str
4  Nan   nan    LocationSummary
5  Month $$$    str
6  Month $$$    str
7  Month $$$    str
8  Month $$$    str
9  Month nan    LocationB
10 Month $$$    str
11 Month $$$    str
12 Month $$$    str
13 Month $$$    str
14 Month nan    LocationSummary
:
:

我的目标是拥有一个像这样的新数据集

  Month Amount Location
0 Month $$$    LocationA
1 Month $$$    LocationA
2 Month $$$    LocationA
3 Month $$$    LocationB
4 Month $$$    LocationB
5 Month $$$    LocationB
6 Month $$$    LocationB
:
:

如您所见,我试图Location通过删除位置摘要范围来清除列,并将 str 替换为壁橱位置名称。我正在考虑像这样循环列:

for x in column location:
    if x==str:
       x=x-1
    else:
       x 
    end
df=df[~df.location.str.contains("summary")]

我永远无法让 for 循环工作,因为如何正确编写迭代字符串。我收到如下错误:

'TypeError: can only concatenate str (not "int") to str'

或不正确的语法

标签: python

解决方案


'TypeError:只能将 str(不是“int”)连接到 str'。这是一个类型转换错误。您必须将该字符串转换为整数才能执行 x - 1 操作。

所以,我相信你的错误就在这条线上

x = x - 1

因为如果 x 是一个字符串,你就不能做那个操作。尝试

x = str(int(x) - 1)

让我解释一下它是如何工作的,因为我认为你对 Python 不是很熟悉

使用 int() 函数,我们将字符串转换为整数。例如,如果 x = '2' with int(x) 我们将得到整数值,而不是字符串值。使用 str() 函数,我们将再次将该整数值转换为字符串。

这就是我的意思:

a = int('2') #Then a will be equal to the integer 2
b = str(2) #Then b will be equal to the string '2' 

推荐阅读