[英]Pandas - Explode multiple columns in pandas and assign value based on the exploded column
[英]Assign value of existing column to new columns in pandas based on multiple conditions
我正在尝试基于现有列在 Pandas 数据框中创建一个新列。
第一列 | 列2 | 第3列 | y1 | y2 | y3 |
---|---|---|---|---|---|
100 | 200 | 300 | 2020年 | 2021年 | 2022年 |
100 | 200 | 300 | 2021年 | 2022年 | 2023 |
100 | 200 | 300 | 2019年 | 2020年 | 2021年 |
我想要一个新列vals如果 currentyear = y1 和 col2 如果 currentyear = y2 则取col1 的值
第一列 | 列2 | 第3列 | y1 | y2 | y3 | 瓦尔斯 |
---|---|---|---|---|---|---|
100 | 200 | 300 | 2020年 | 2021年 | 2022年 | 200 |
100 | 200 | 300 | 2021年 | 2022年 | 2023 | 100 |
100 | 200 | 300 | 2019年 | 2020年 | 2021年 | 300 |
我正在尝试以下代码:
def assignvalues(df):
if df['y1'] == currentyear:
df['Vals'] = df['col1']
elif df['y2'] == currentyear:
df['Vals'] = df['col2']
elif df['y3'] == currentyear:
df['Vals'] = df['col3']
df.apply(assignvalues)
它确实创建列但不存储任何值。
从您的DataFrame
:
>>> import pandas as pd
>>> from io import StringIO
>>> df = pd.read_csv(StringIO("""
... column1,column2,column3,y1,y2,y3
... 100,200,300,2020,2021,2022
... 100,200,300,2021,2022,2023
... 100,200,300,2019,2020,2021"""))
>>> df
column1 column2 column3 y1 y2 y3
0 100 200 300 2020 2021 2022
1 100 200 300 2021 2022 2023
2 100 200 300 2019 2020 2021
以及函数assignvalues
,它现在返回每个if
的预期列中的值。 例如,我们将当前currentyear
设置为2021
:
>>> def assignvalues(df):
... if df['y1'] == currentyear:
... return df['column1']
... elif df['y2'] == currentyear:
... return df['column2']
... elif df['y3'] == currentyear:
... return df['column3']
>>> currentyear = 2021
我们可以为df["Vals"]
分配一个apply()
,就像您所做的那样,使用axis=1
参数来获得预期结果:
>>> df["Vals"] = df.apply(assignvalues, axis=1)
>>> df
column1 column2 column3 y1 y2 y3 Vals
0 100 200 300 2020 2021 2022 200
1 100 200 300 2021 2022 2023 100
2 100 200 300 2019 2020 2021 300
您可以使用np.select()
来加快执行速度,如下所示:
import numpy as np
currentyear = pd.to_datetime('now').year
condlist = [df['y1'] == currentyear,
df['y2'] == currentyear,
df['y3'] == currentyear]
choicelist = [df['column1'],
df['column2'],
df['column3']]
df['Vals'] = np.select(condlist, choicelist, default=np.nan)
如果 currentyear 没有匹配项的默认值为NaN
,您可以通过修改default=
参数将其设置为 0 或您选择的其他值。
结果:
print(df)
column1 column2 column3 y1 y2 y3 Vals
0 100 200 300 2020 2021 2022 200
1 100 200 300 2021 2022 2023 100
2 100 200 300 2019 2020 2021 300
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.