问题
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