我有这个数据框架:
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'categories': ['cat0', 'cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6', 'cat7'],
'points': [5, 17, 7, 19, 12, 13, 9, 24]})
我有这个函数从这个数据框创建短语:
def conteo_frase(data):
print(f"We have in total {len(df1)} categories")
print(f"---------------------TOP RANKED------------------")
print(f"The most important category is {df.loc[0].categories} with a total of {df.loc[0].points}")
print(f"The 2nd most important category is {df.loc[1].categories} with a total of {data.loc[1].points}")
我想为数据框中的每一行创建一个注释,并为每一行创建一个for循环。
的例子:
We have in total 7 categories
---------------------TOP RANKED------------------
The most important category is cat0 with a total of 5
The 2nd most important category is cat1 with a total of 17
The 3rd most important category is cat2 with a total of 7
but for each row of the dataframe.
您可以在数据框的每一行上使用apply()
。此解决方案的唯一警告是,您必须单独打印标题:
# Function to get ordinal number string from integer
def ordinaltg(n):
return str(n) + {1: 'st', 2: 'nd', 3: 'rd'}.get(4 if 10 <= n % 100 < 20 else n % 10, "th")
# Modified version of conte_frase
def conteo_frase(row):
print(f"The {ordinaltg(row.name+1)} important category is {row.categories} with a total of {row.points}")
df1 = pd.DataFrame({'categories': ['cat0', 'cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6', 'cat7'],
'points': [5, 17, 7, 19, 12, 13, 9, 24]})
# Your header
print(f"We have in total {len(df1)} categories")
print(f"---------------------TOP RANKED------------------")
# Using apply on rows
df1.apply(conteo_frase, axis=1)
这是我们看到的输出:
We have in total 8 categories
---------------------TOP RANKED------------------
The 1st important category is cat0 with a total of 5
The 2nd important category is cat1 with a total of 17
The 3rd important category is cat2 with a total of 7
The 4th important category is cat3 with a total of 19
The 5th important category is cat4 with a total of 12
The 6th important category is cat5 with a total of 13
The 7th important category is cat6 with a total of 9
The 8th important category is cat7 with a total of 24
如果你想阅读更多关于apply()
的内容,这里是链接。