【发布时间】:2021-03-03 18:28:20
【问题描述】:
我看到很多帖子都用 iterrows() 强调了这种行为,但是我们正在用 .columns 和 .dtypes 观察它。
这里有两段关键代码
#1。一个简单的循环遍历数据帧
for col in df.columns:
print("hello")
#A line of code that performs a join with the dataframe
files = target.join(df, primaryKeys, 'inner').select(col("filepath").alias("filepath1")).distinct()
如果没有 for 循环,这可以正常工作。但是,当上面的 for 循环未注释时,这会失败,因为 'str' object is not callable。如果我们尝试使用
for col in df.dtypes:
print("hello")
失败了
'tuple' 对象不可调用。
我也试过
select_expr = [
col(c).cast("smallint") if t == "tinyint)" else col(c) for c, t in df4.dtypes
]
df4 = df4.select(*select_expr)
失败了
'str' 对象不可调用。
为什么迭代 for 循环的行为会导致连接失败?迭代是否会以某种方式改变底层数据框?我之前已经看到 iterrows 发生过这种情况,但是正如我在上面展示的那样,有很多使用列/dtypes 的代码示例都可以正常工作。
【问题讨论】:
-
可能是因为您将
col定义为一些列名称列表,然后用迭代时使用的变量(存储元组或字符串)覆盖它 -
@ALollz 你说的完全正确
标签: python pandas apache-spark pyspark