首页 > 解决方案 > 将列表作为列添加到数据框

问题描述

假设我有以下列表:

cond_1 = [1,2]
cond_2 = [3,5]

还有以下数据框df

|----------|
| Column_1 |
|----------|
|     x    |
|----------|
|     y    |
|----------|
|     y    |
|----------|
|     x    |
|----------|

我想要做的是添加第二列Column_2。遵循这些标准:

1) 如果Column_1包含 a ,则在fromx中添加一个值;Column_2cond_1

2) 如果Column_1包含 a ,则在fromy中添加一个值Column_2cond_2

所需的输出应该是这样的:

|----------|----------|
| Column_1 | Column_2 |
|----------|----------|
|     x    |     1    |
|----------|----------|
|     y    |     3    |
|----------|----------|
|     y    |     5    |
|----------|----------|
|     x    |     2    |
|----------|----------|

我一直在尝试使用pd.Series

df_x = df.loc[df['Column_1'] == "x"] #first I create a dataframe only with the x values
df_x['Column_2'] = pd.Series(cond_1)

然后我会为这些y值重复同样的事情,获得df_y​​ .

但是,这不会成功。然后,我需要再次附加两个数据帧(df_xdf_y),并且我丢失了我想要从中维护的原始索引的信息df

标签: pythonpython-3.xpandasdataframe

解决方案


您可以创建一个辅助类并在 中使用它.apply,例如:

class ReplaceWithNext:
    def __init__(self, **kwargs):
        self.lookup = {k: iter(v) for k, v in kwargs.items()}
    def __call__(self, value):
        return next(self.lookup[value])

然后将其用作:

df['Column_2' ] = df['Column_1'].apply(ReplaceWithNext(x=cond_1, y=cond_2))

这会给你:

  Column_1  Column_2
0        x         1
1        y         3
2        y         5
3        x         2

推荐阅读