pandas edit a cell value with itertuples

烈酒焚心 提交于 2019-12-22 09:37:01

问题


I would like speed my code, so I don't like to use double for: my code:

    for c in range(0, n-1):
        for l in range(0,n-c-1):
            df2.ix[l,c]=C_back(l,c,df)

I would like to use

for x in df.itertuples():

but I don't know how to modify a specific cell value. thanks


回答1:


use stack

for mytuple, value in df.stack().iteritems():
    print(mytuple, value)

consider the df

df = pd.DataFrame(np.arange(9).reshape(-1, 3), list('ABC'), list('XYZ'))
df

for mytuple, value in df.stack().iteritems():
    print(mytuple, value)

('A', 'X') 0
('A', 'Y') 1
('A', 'Z') 2
('B', 'X') 3
('B', 'Y') 4
('B', 'Z') 5
('C', 'X') 6
('C', 'Y') 7
('C', 'Z') 8

To set the values of df

for (i, j), value in df.stack().iteritems():
    df.set_value(i, j, value ** 2)

df



来源:https://stackoverflow.com/questions/40536812/pandas-edit-a-cell-value-with-itertuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!