在 Pandas 数据框上应用列表

Apply list over Pandas dataframe

我需要按列将列表应用于 pandas 数据框。要执行的操作是字符串连接。更具体一点:

我的输入:

df = pd.DataFrame([['a', 'b', 'c'], ['d', 'e', 'f']], columns=['Col1', 'Col2', 'Col3'])
lt = ['Prod1', 'Prod2', 'Prod3']

这导致:

>>>df
Col1 Col2 Col3
0    a    b    c
1    d    e    f

>>>lt
['Prod1', 'Prod2', 'Prod3']

此外,lt的长度总是等于df的列数。

我想要的是这样的数据框:

res = pd.DataFrame([['Prod1a', 'Prod2b', 'Prod3c'], ['Prod1d', 'Prod2e', 'Prod3f']],
               columns=['Col1', 'Col2', 'Col3'])

给出:

>>>res
Col1    Col2    Col3
0  Prod1a  Prod2b  Prod3c
1  Prod1d  Prod2e  Prod3f

直到现在,我已经能够解决遍历行和列的问题,但我不会放弃有更优雅的方法来解决它的想法(也许像 apply.

有人有什么建议吗?谢谢!

您可以执行广播字符串连接:

lt + df

     Col1    Col2    Col3
0  Prod1a  Prod2b  Prod3c
1  Prod1d  Prod2e  Prod3f

你也可以使用numpy的np.char.add函数。

df[:] = np.char.add(lt, df.values.astype(str))
df    
     Col1    Col2    Col3
0  Prod1a  Prod2b  Prod3c
1  Prod1d  Prod2e  Prod3f

第三,列表理解选项。

df[:] = [[i + v for i, v in zip(lt, V)] for V in df.values.tolist()]
df

     Col1    Col2    Col3
0  Prod1a  Prod2b  Prod3c
1  Prod1d  Prod2e  Prod3f