python - 通过循环函数中的每一行来修改数据框

标签 python python-2.7 function pandas dataframe

我尝试通过循环行并返回修改后的数据帧来通过函数修改数据帧。在下面的代码中,我将数据帧“ding”传递给函数“test”,并通过迭代每一行并返回修改后的数据帧来创建新列“C”。我预计 test_ding df 有 3 列,但只能看到两列。非常感谢任何帮助。

附注它可以有其他更简单的方法来完成这个小任务,但我希望迭代行,并希望看到对数据帧所做的修改反射(reflect)在函数之外

s1 = pd.Series([1,3,5,6,8,10,1,1,1,1,1,1])
s2 = pd.Series([4,5,6,8,10,1,7,1,6,5,4,3])

ding=pd.DataFrame({'A':s1,'B':s2})

def test(ding):
   for index,row in ding.iterrows():
       row['C']=row.A+row.B
return ding

test_ding=test(ding)

最佳答案

您可以在原始数据框上而不是在上使用set_valueset_valuepretty fast如果您想逐个单元格设置值:

def test(ding):
    for index, row in ding.iterrows():
        ding.set_value(index, 'C', row.A+row.B)
    return ding
​
test_ding=test(ding)

test_ding
#   A   B   C
#0  1   4   5.0
#1  3   5   8.0
#2  5   6   11.0
# ...

关于python - 通过循环函数中的每一行来修改数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43926522/

相关文章:

python - 如何在不覆盖的情况下将键/值对插入嵌套字典中?

python - zlib 模块丢失

function - 方案 lambda 函数中的默认参数?

java - EclipseLink(版本 2.1.3)中 JQPL 中的 Oracle NVL 函数是否等效?

python - urllib2 - 能够跳过证书验证

Python 将长度列为字符串

python - Python 中的文本文件到元组到字典

python - 从 Python 中的字典中提取彼此不相等的随机键

c# - 从统一命名空间中的另一个类(在克隆对象上)获取一个函数,c#

Python .append() 到一行中的向量