我正在使用脚本重新格式化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'
或语法错误
'TypeError:只能将str(而不是“ int”)连接到str'。这是类型转换错误。您必须将该字符串转换为整数才能执行x-1操作。
所以,我相信您的错误即将来临
x = x - 1
因为如果x是字符串,则无法执行该操作。尝试
x = str(int(x) - 1)
让我解释一下它是如何工作的,因为我认为您对Python不太熟悉
使用int()函数,我们将字符串转换为整数。例如,如果x ='2'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'