gpt4 book ai didi

python - 使用 [key :value] combination in Python 将多列合并为一个列列表

转载 作者:行者123 更新时间:2023-11-28 17:13:35 25 4
gpt4 key购买 nike

让我通过注意组合列不是字典来作为这个问题的序言。生成的数据框在“组合”列中有方括号 - 因此它看起来像数据框内的列表,格式为 [key1:value1, key2:value2, etc]。

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

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

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

   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']

试图将数据帧转换为每行的字典,但无法将其转换为列表。

test['combined'] = test.to_dict(orient='records')

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

以前在这里问过这个问题,但想澄清这个问题标题中的问题。 How to Create a List from a Dictionary within a DataFrame in Python

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

最佳答案

你可以使用 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]

关于python - 使用 [key :value] combination in Python 将多列合并为一个列列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45682068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com