从pandas Dataframe 的每一行创建一个字符串短语

8yparm6h  于 2023-04-04  发布在  其他
关注(0)|答案(1)|浏览(101)

我有这个 Dataframe :

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]})

我有这个函数来从这个dataframe创建短语:

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}")

我想为dataframe中的每一行创建一个注解,并为每一行创建一个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.
bejyjqdl

bejyjqdl1#

你可以在 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()这里是链接。

相关问题