pandas 如何在panda中的特定列添加列表值?

lsmepo6l  于 2023-01-07  发布在  其他
关注(0)|答案(2)|浏览(119)

假设我有以下 Dataframe :

df = pd.DataFrame({'sample': ['sample 1', 'sample 2'],
                   'values': [[0.2, 0.3, 0.5],[0.3, 0.3, 0.4]],
                   'group': [1, 0]})

输出:

sample         values      group
0   sample 1    [0.2, 0.3, 0.5] 1
1   sample 2    [0.3, 0.3, 0.4] 0

以及一组

lst=[0, 1, 2]

这是我的预期输出:

zxlwwiss

zxlwwiss1#

你可以试试这个:

import numpy as np

new_df = pd.DataFrame(np.repeat(df.values, len(lst), axis=0), columns=df.columns)
new_lst = lst * len(df)
new_df['group'] = new_lst
print(new_df)

输出:

sample           values  group
0  sample 1  [0.2, 0.3, 0.5]      0
1  sample 1  [0.2, 0.3, 0.5]      1
2  sample 1  [0.2, 0.3, 0.5]      2
3  sample 2  [0.3, 0.3, 0.4]      0
4  sample 2  [0.3, 0.3, 0.4]      1
5  sample 2  [0.3, 0.3, 0.4]      2
g2ieeal7

g2ieeal72#

使用十字merge

out = df.drop(columns='group').merge(pd.Series(lst, name='group'), how='cross')

输出:

sample           values  group
0  sample 1  [0.2, 0.3, 0.5]      0
1  sample 1  [0.2, 0.3, 0.5]      1
2  sample 1  [0.2, 0.3, 0.5]      2
3  sample 2  [0.3, 0.3, 0.4]      0
4  sample 2  [0.3, 0.3, 0.4]      1
5  sample 2  [0.3, 0.3, 0.4]      2

相关问题