Python中使用[key:value]组合将多列合并为一列列表

swe*_*low 6 python dataframe pandas

让我在这个问题前指出,组合列不是字典。生成的数据帧在“组合”列中包含方括号 - 因此它看起来像数据帧中格式为 [key1:value1、key2:value2 等] 的列表。

我正在尝试从此转换我的数据框:

import pandas as pd
test = pd.DataFrame({'apples':['red','green','yellow'], 'quantity':
[1,2,3],'tasteFactor':['yum','yum','yuck']})

   apples  quantity tasteFactor
0     red         1         yum
1   green         2         yum
2  yellow         3        yuck
Run Code Online (Sandbox Code Playgroud)

对于这种格式,它将每行中的键与值组合到一个新列中:

   apples  quantity tasteFactor  combined
0     red         1         yum  ['apples':'red','quantity':'1','tastefactor':'yum']
1   green         2         yum  ['apples':'green','quantity':'2','tastefactor':'yum']
2  yellow         3        yuck  ['apples':'yellow','quantity':'3','tastefactor':'yuck']
Run Code Online (Sandbox Code Playgroud)

尝试将数据帧转换为每行的字典,但在将其转换为列表时遇到困难。

test['combined'] = test.to_dict(orient='records')
Run Code Online (Sandbox Code Playgroud)

生成的新列不需要是实际的列表类型。它可能是一个字符串。

以前在这里问过这个问题,但想澄清这个问题标题中的问题。 如何在 Python 中从 DataFrame 中的字典创建列表

找到了以下密切相关的问题并尝试了它们的推导,这让我成功了一半,但似乎无法获得完全正确的格式。

Clo*_*ave 3

您可以使用 pandas dataframes 的 apply 方法来完成

import pandas as pd
df = pd.DataFrame({'apples':['red','green','yellow'], 'quantity':
[1,2,3],'tasteFactor':['yum','yum','yuck']})

col_names = df.columns

def func(row):
    global col_names
    list_ = [str(b)+':'+str(a) for a,b in zip(row,col_names.values.tolist())]
    return list_

x = list(map(func, df.values.tolist()))
df.loc[:,'combined'] = pd.Series(x)
# df
#    apples  quantity tasteFactor                                       combined
# 0     red         1         yum      [apples:red, quantity:1, tasteFactor:yum]
# 1   green         2         yum    [apples:green, quantity:2, tasteFactor:yum]
# 2  yellow         3        yuck  [apples:yellow, quantity:3, tasteFactor:yuck]
Run Code Online (Sandbox Code Playgroud)