简体   繁体   English

通过另一个列的值映射数据框列的值

[英]Map dataframe column value by another column's value

My dataframe has a month column with values that repeat as Apr , Apr.1 , Apr.2 etc. because there is no year column. 我的数据帧具有与重复的值的月柱AprApr.1Apr.2等因为没有年列。 I added a year column based on the month value using a for loop as shown below, but I'd like to find a more efficient way to do this: 我使用for循环根据月值添加了year列,如下所示,但我想找到一种更有效的方法:

Products['Year'] = '2015'
for i in range(0, len(Products.Month)):
    if '.1' in Products['Month'][i]:
        Products['Year'][i] = '2016'
    elif '.2' in Products['Month'][i]:
        Products['Year'][i] = '2017'

You can use .str and treat the whole columns like string to split at the dot. 您可以使用.str并将整列视为字符串,以在点处分割。 Now, apply a function that takes the number string and turns into a new year value if possible. 现在,应用一个函数,该函数将数字字符串转换为新的年份值(如果可能)。

Starting dataframe: 起始数据帧:

   Month
0    Apr
1  Apr.1
2  Apr.2

Solution: 解:

def get_year(entry):
    value = 2015
    try:
        value += int(entry[-1])
    finally:
        return str(value)

df['Year'] = df.Month.str.split('.').apply(get_year)

Now df is: 现在df是:

   Month  Year
0    Apr  2015
1  Apr.1  2016
2  Apr.2  2017

You can use pd.to_numeric after splitting and add 2015 ie 您可以在拆分后使用pd.to_numeric并添加2015

df['new'] = pd.to_numeric(df['Month'].str.split('.').str[-1],errors='coerce').fillna(0) + 2015

# Sample DataFrame from @ Mike Muller
   Month  Year     new
0    Apr  2015  2015.0
1  Apr.1  2016  2016.0
2  Apr.2  2017  2017.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Map 通过搜索另一个新列的值 dataframe - Map the value of a new column by searching another dataframe 如何根据另一个 dataframe 列的值设置列中的值 - How set value in column according to another dataframe column's value 根据另一列和字典值填充熊猫的 dataframe 列 - Populate a panda's dataframe column based on another column and dictionary value 如果值在另一个 dataframe 的另一列中,则添加列 - Add column if value is in another column of another dataframe 如何将数据框的值复制到另一个数据框的最后一列/行 - How to copy value of dataframe to another dataframe's last column/row 如何将一列除以另一列,其中一个数据帧的列值对应于 Python Pandas 中另一个数据帧的列值? - How to divide one column by another where one dataframe's column value corresponds to another dataframe's column's value in Python Pandas? 如何根据另一个数据框的值返回列中的值 - How to return a value in a column based on another's dataframe's values 多个 if/then 评估数据框中列的值并有条件地修改另一列值的最佳方法是什么? - What is the optimal method for multiple if/then's to evaluate a column's value in a dataframe and conditionally modify another column value? 如何使用条件将一个数据框列的值与另一个数据框列的值匹配? - How do you match the value of one dataframe's column with another dataframe's column using conditionals? python pandas:检查数据帧的列值是否在另一个数据帧的列中,然后计数并列出它 - python pandas: Check if dataframe's column value is in another dataframe's column, then count and list it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM