Python 如何向下循环并用列中的特定值替换下一行的值
我正在用脚本重新格式化excel文件,这是我正在使用的数据集Python 如何向下循环并用列中的特定值替换下一行的值,python,Python,我正在用脚本重新格式化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 $$$
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
,方法是去掉Location summary range并用clock Location name替换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'
请提供MCVE。请参阅:。你看过熊猫的文件了吗?你不能指望别人为你做所有的工作。