在Pandas数据框上应用列表

2024-10-03 21:25:11 发布

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

我需要按列对数据帧应用列表。要执行的操作是字符串串联。更具体地说:

我的输入:

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的东西)。你知道吗

有人有什么建议吗?谢谢!你知道吗


Tags: columns数据ltdataframedfrescol2col3
1条回答
网友
1楼 · 发布于 2024-10-03 21:25:11

可以执行广播字符串串联:

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

相关问题 更多 >