python - 将列表作为列添加到数据框
问题描述
假设我有以下列表:
cond_1 = [1,2]
cond_2 = [3,5]
还有以下数据框df
:
|----------|
| Column_1 |
|----------|
| x |
|----------|
| y |
|----------|
| y |
|----------|
| x |
|----------|
我想要做的是添加第二列Column_2
。遵循这些标准:
1) 如果Column_1
包含 a ,则在fromx
中添加一个值;Column_2
cond_1
2) 如果Column_1
包含 a ,则在fromy
中添加一个值Column_2
cond_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_x
和df_y
),并且我丢失了我想要从中维护的原始索引的信息df
。
解决方案
您可以创建一个辅助类并在 中使用它.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
推荐阅读
- python - 每次都调用 Microsoft Graph API 而不刷新对 API 的授权
- mongodb - 使用该文档上存在的值更新每个文档上的值
- swagger - 如何在 openApi 项目中的 requestBody 对象上指定所需的属性?
- flutter - 如何在 Flutter 中初始化所有 TabBarView
- reactjs - 加载本地图像时反应“未找到模块”
- python - Looping a variable cyclically
- pandas - Pandas 使用特定字符串和数组/列表选择数据框列
- linux - 在 Ubuntu 19.10 arm64 上编译 Scilab 6.1 git 时出错?
- python - 如何让机器人点击下载按钮?
- windows-10 - 受控文件夹访问阻止了成像器,但通知栏中没有来自 Windows Defender 的通知