如何在 pandas 的应用函数中获取所有 df 数据
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)
上面代码给出的错误:AttributeError:'Series'对象没有属性'columns'请求你帮我更正高亮方法代码。
row
在你的函数中将是一个 series
。 Apply with axis=1 一次向函数发送一行。无需申请即可实现您的尝试。
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'])
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)
上面代码给出的错误:AttributeError:'Series'对象没有属性'columns'请求你帮我更正高亮方法代码。
row
在你的函数中将是一个 series
。 Apply with axis=1 一次向函数发送一行。无需申请即可实现您的尝试。
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'])