将列表作为列添加到数据框中

gio*_*o-p 3 python dataframe python-3.x pandas

假设我有以下列表:

cond_1 = [1,2]
cond_2 = [3,5]
Run Code Online (Sandbox Code Playgroud)

还有以下数据框df

|----------|
| Column_1 |
|----------|
|     x    |
|----------|
|     y    |
|----------|
|     y    |
|----------|
|     x    |
|----------|
Run Code Online (Sandbox Code Playgroud)

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

1) 如果Column_1包含 a x,则在Column_2from 中添加一个值cond_1

2) 如果Column_1包含 a y,则在Column_2from 中添加一个值cond_2

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

|----------|----------|
| Column_1 | Column_2 |
|----------|----------|
|     x    |     1    |
|----------|----------|
|     y    |     3    |
|----------|----------|
|     y    |     5    |
|----------|----------|
|     x    |     2    |
|----------|----------|
Run Code Online (Sandbox Code Playgroud)

我一直在尝试使用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)
Run Code Online (Sandbox Code Playgroud)

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

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

Jon*_*nts 7

您可以创建一个辅助类并在 中使用它.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])
Run Code Online (Sandbox Code Playgroud)

然后将其用作:

df['Column_2' ] = df['Column_1'].apply(ReplaceWithNext(x=cond_1, y=cond_2))
Run Code Online (Sandbox Code Playgroud)

这会给你:

  Column_1  Column_2
0        x         1
1        y         3
2        y         5
3        x         2
Run Code Online (Sandbox Code Playgroud)