Consider an empty dataframe (df) with countries for index and status for columns.
df = pd.DataFrame({'Country': ['Albania', 'France', 'Mexico', 'Russia'],
'On': [0, 0, 0, 0],
'Off': [0, 0, 0, 0]}).set_index('Country')
How do I apply a function to each cell in the dataframe with the index name and column name as arguments to the function? I would like to replace row(x) and column(x) with syntax that would make this work.
df = df.apply(lambda x : function(row(x), column(x)))
Thank you
You can do something like that
def fct(row):
# You can get index with row.name
print(row.name)
# You can set separately row["On"] and row["Off"]
print(row["On"])
print(row["Off"])
row["On"] = row["On"] + 1
row["Off"] = row["Off"] + 2
return row
dff = df.apply(fct, axis=1)
Edit: If you definitely need to use a function dependant of the row and column, would this solutions work for you?
def f2(row, col):
# ...
def fct(row):
# You can get index with row.name
row_name = row.name
for column_name in row.index.values:
row[v] = f2(row_name, column_name)
return row
dff = df.apply(fct, axis=1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.