我有一个包含数字列的数据框,还有一个元组列表和一个字符串列表。 元组列表表示应添加的值,其中该列表中的每个索引对应于数据框中的数字列。字符串列表表示要添加的列的名称。
示例:
import pandas as pd
df = pd.DataFrame({'number':[0,0,1,1,2,2,3,3]})
# a list of keys and a list of tuples
keys = ['foo','bar']
combinations = [('99%',0.9),('99%',0.8),('1%',0.9),('1%',0.8)]
预期输出:
number foo bar
0 0 99% 0.9
1 0 99% 0.9
2 1 99% 0.8
3 1 99% 0.8
4 2 1% 0.9
5 2 1% 0.9
6 3 1% 0.8
7 3 1% 0.8
最佳答案
原帖
要获得该输出,您可以尝试
df2 = pd.DataFrame(combinations, columns = keys)
pd.concat([df, df2], axis=1)
返回
number foo bar
0 0 99% 0.9
1 1 99% 0.8
2 2 1% 0.9
3 3 1% 0.8
编辑
根据您的新要求,您可以使用以下内容
df.set_index('number', inplace=True)
df = df.merge(df2, left_index = True, right_index=True)
df = df.reset_index().rename(columns={'index':'number'})
这也适用于不同的重复数量,即
df = pd.DataFrame({'number':[0,0,1,1,1,2,2,3,3,3]})
返回
number foo bar
0 0 99% 0.9
1 0 99% 0.9
2 1 99% 0.8
3 1 99% 0.8
4 1 99% 0.8
5 2 1% 0.9
6 2 1% 0.9
7 3 1% 0.8
8 3 1% 0.8
9 3 1% 0.8
关于python - 根据现有数字列、字符串列表作为列名称以及元组列表作为值在数据框中创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60455173/