python - 根据现有数字列、字符串列表作为列名称以及元组列表作为值在数据框中创建新列

标签 python pandas

我有一个包含数字列的数据框,还有一个元组列表和一个字符串列表。 元组列表表示应添加的值,其中该列表中的每个索引对应于数据框中的数字列。字符串列表表示要添加的列的名称。

示例:

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/

相关文章:

python - 将 Python virtualenv 移植到另一个系统

python - 从linux中的 Pandas 数据框列中减去日期

python - 'str' 对象没有属性 'map'

pandas - 根据pandas中给定的特定条件从给定的日期创建year_category

python - 使用 Pandas 和 .shift 查询带条件的 .csv 文件

Python pexpect 没有按预期工作

python - 索引错误: index 3 is out of bounds for axis 0 with size 3 pygame

python - GDB 在给定内存区域中查找指针

python - pycrypto:无法解密文件

python - 在具有结构化数据的列上合并 Pandas Dataframe