同时迭代两个dataframe列,并将每个列的值返回到不同的位置

2024-05-19 12:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种解决方案,可以同时迭代两个dataframe列,然后从每个列中获取值,并将它们放在文本中两个不同的位置。你知道吗

到目前为止我的代码是:

def fetchingMetaTitle(x):
    keywords = df['Keyword']
    title1 = f'{x.title()} - We have a great selection of {x} | Example.com'
    title2 = f'{x.title()} - Choose among several {x} here | Example.com'
    title3 = f'{x.title()} - Buy cheap {x} easy and fast | Example.com'
    for i in keywords:
        if i.lower() in x.lower():
            return random.choice([title1,title2,title3])
    else:
        return np.nan

df['Category Meta Title'] = df['Keyword'].apply(fetchingMetaTitle)

结果如下:

+---------+----------------+-----------------------------------------------------------+
| Keyword | Category Title |                    Category Meta Title                    |
+---------+----------------+-----------------------------------------------------------+
| jeans   | blue jeans     | Jeans - We have a great selection of jeans | Example.com  |
| jackets | red jackets    | Jackets - Choose among several jackets here | Example.com |
| shoes   | black shoes    | Shoes - Buy cheap shoes easy and fast | Example.com       |
+---------+----------------+-----------------------------------------------------------+

目前,我只从df['Keyword']获取值,并在两个位置将值返回到df['Category Meta Title']。我不想添加两次,而是将df['Category Title']中的值添加为第二个值。你知道吗

结果如下:

+---------+----------------+---------------------------------------------------------------+
| Keyword | Category Title |                      Category Meta Title                      |
+---------+----------------+---------------------------------------------------------------+
| jeans   | blue jeans     | Jeans - We have a great selection of blue jeans | Example.com |
| jackets | red jackets    | Jackets - Choose among several red jackets here | Example.com |
| shoes   | black shoes    | Shoes - Buy cheap black shoes easy and fast | Example.com     |
+---------+----------------+---------------------------------------------------------------+

提前谢谢!你知道吗


Tags: comdftitleexamplehavekeywordmetawe
2条回答

您可以创建一个新列,并将一个句子的模板和这两个参数放在其中。这将满足您对访问两个原始列中的行值的要求。在下一步中,您可以应用一个自定义函数,该函数为您创建句子并将它们放在res列中。你知道吗

import pandas as pd

df = pd.DataFrame({'A':['aa','bb','cc'], 'B':['a','b','c'], 'C':['1.{}, {}', '2.{}, {}', '3.{}, {}']})

df['combined'] = df[['A','B','C']].values.tolist()
df['res'] = df['combined'].apply(lambda x: x[2].format(x[0], x[1]))

print(df['res'])

使用此方法,基于以下数据帧df

    A  B         C
0  aa  a  1.{}, {}
1  bb  b  2.{}, {}
2  cc  c  3.{}, {}

输出为:

0    1.aa, a
1    2.bb, b
2    3.cc, c

IIUC,此函数将使用^{}语法而不是f'{string}'格式执行您需要的操作:

def fetchingMetaTitle(row):
    title1 = '{} - We have a great selection of {} | Example.com'.format(
                     row['Keyword'].title(), row['Category Title'])
    title2 = '{} - Choose among several {} here | Example.com'.format(
                     row['Keyword'].title(), row['Category Title'])
    title3 = '{} - Buy cheap {} easy and fast | Example.com'.format(
                     row['Keyword'].title(), row['Category Title'])
    return random.choice([title1,title2,title3])

df['Category Meta Title '] = df.apply(fetchingMetaTitle, axis=1)

>>> df
   Keyword Category Title                               Category Meta Title 
0    jeans     blue jeans  Jeans - Choose among several blue jeans here |...
1  jackets    red jackets  Jackets - We have a great selection of red jac...
2    shoes    black shoes  Shoes - Buy cheap black shoes easy and fast | ...

或者,使用f'{string}'方法:

def fetchingMetaTitle(row):
    keyword = row['Keyword'].title()
    cat = row['Category Title']
    title1 = f'{keyword} - We have a great selection of {cat} | Example.com'
    title2 = f'{keyword} - Choose among several {cat} here | Example.com'
    title3 = f'{keyword} - Buy cheap {cat} easy and fast | Example.com'
    return random.choice([title1,title2,title3])

df['Category Meta Title '] = df.apply(fetchingMetaTitle, axis=1)

会做同样的事。你知道吗

注意:我不太清楚您的if语句的目标是什么,因此如果您澄清这一点,我可以尝试将其功能插入到上面的函数中。。。你知道吗

相关问题 更多 >