[英]How to get all df data inside apply function of pandas
import pandas as pd
test_df =pd.DataFrame({"col1":[1,12,3,4],
"col2":[3,14,5,6],
"col3":[4,5,6,7]})
print(test_df)
col1 col2 col3
0 1 3 4
1 12 14 5
2 3 5 6
3 4 6 7
def highlight(row):
df1 = pd.DataFrame('', index=row.index, columns=row.columns)
# set columns by condition
df1.loc[row['col2'] == 5, 'col2'] = "AA"
df1.loc[row['col3'] == 5, 'col3'] = "BB"
return ret
df_output= test_df.apply(highlight, axis=1)
Error given above code: AttributeError: 'Series' object has no attribute 'columns' Request you please help me to correct highlight method code.上面代码给出的错误: AttributeError: 'Series' object has no attribute 'columns' 请您帮我更正突出显示方法代码。
row
inside you function will be a series
. row
在你里面 function 会是一个series
。 Apply with axis=1 sends to the function one row at time. Apply with axis=1 一次发送到 function 一行。 What you are trying can be achieved without an apply.无需申请即可实现您正在尝试的目标。
test_df.loc[test_df.col2==5, 'col2'] = "AA"
def highlight(row):
ret = [ i for i in row.values]
# set columns by condition
if row['col2'] == 5:
ret[row.index.get_loc('col2')] ="AA"
if row['col3'] == 5:
ret[row.index.get_loc('col3')] ="BB"
return ret
data= test_df.apply(highlight, axis=1)
d= data.tolist()
s= pd.DataFrame(d, index=[1,2,3,4],columns=['col1','col2','col3'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.