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 $$$ 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' 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'
推荐阅读
- sql - SQL Server 中 group by 子句中的前 1 名?
- google-apps-script - 如何从侧边栏填充特定列?
- lua - lua 脚本如何调用它没有导入的函数?
- autohotkey - ; 作为新的修饰键
- php - 当我想按顺序订购时,Php,usort() 失败
- r - 如何将所有可能的字段划分到R中的矩阵中
- django - Django - NoReverseMatch 错误,模板 URL 中有两个 slug
- c# - Unity3d 找不到资源命名空间
- outlook - Outlook Web 加载项在 Outlook 2013 桌面客户端中不起作用
- amazon-iam - AWS 将特定 ECR 图像限制为特定 IAM 用户?