繁体   English   中英

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

[英]Merge multiple columns into one column list with [key:value] combination in Python

让我通过注意组合列不是字典来预先提出这个问题。 结果数据框在“组合”列中具有方括号 - 因此它看起来像数据框中的列表,格式为[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

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

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

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

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

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

您可以使用pandas数据帧的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]

如您所述,生成的新列不需要是实际的列表类型。

di=test.T.to_dict()
test['Mapper']=test.index
test.Mapper.map(di)
test.assign(combined=test.Mapper.map(di)).drop('Mapper',1)


Out[493]: 
   apples  quantity tasteFactor                                           combined
0     red         1         yum  {'apples': 'red', 'quantity': 1, 'tasteFactor'...
1   green         2         yum  {'apples': 'green', 'quantity': 2, 'tasteFacto...
2  yellow         3        yuck  {'apples': 'yellow', 'quantity': 3, 'tasteFact...

编辑:

di=test.T.to_dict()
test['Mapper']=test.index
test.Mapper.map(di)
test=test.assign(combined=test.Mapper.map(di).astype(str)).drop('Mapper',1)
test=test.combined.str.replace('{','[').str.replace('}',']')


test.combined[0]
Out[511]: "['apples': 'red', 'quantity': 1, 'tasteFactor': 'yum']"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM