我需要遍历一个数据帧并生成一列,该列将工作日转换为其相关数字.

我得出了以下结论:

 inputData['DOW'] = ""
    for i in range(0,len(inputData)):
        if 'Sunday' in inputData.iloc[i]['day_of_the_week']:
            inputData.iloc[i]['DOW']=1
        elif 'Monday' in inputData.iloc[i]['day_of_the_week']:
           inputData.iloc[i]['DOW']=2
        elif 'Tuesday' in inputData.iloc[i]['day_of_the_week']:
           inputData.iloc[i]['DOW']=3
        elif 'Wednesday' in inputData.iloc[i]['day_of_the_week']:
           inputData.iloc[i]['DOW']=4
        elif 'Thursday' in inputData.iloc[i]['day_of_the_week']:
            inputData.iloc[i]['DOW']=5
        elif 'Friday' in inputData.iloc[i]['day_of_the_week']:
            inputData.iloc[i]['DOW']=6
        elif 'Saturday' in inputData.iloc[i]['day_of_the_week']:
            inputData.iloc[i]['DOW']=7

但这让我返回所有行的"DOW"列为空...这里怎么了?

推荐答案

我不会详细解释为什么这是错误的——但这在许多层面上都是错误的.您可以使用replace简单地重新映射

import pandas as pd
mapping = {
    'Sunday': 0,
    'Monday': 1,
    'Tuesday': 2,
    'Wednesday': 3,
}
df = pd.DataFrame(data=['Monday', 'Tuesday', 'Wednesday', 'Monday'], columns=['day_of_week'])
df['DOW'] = df['day_of_week'].replace(mapping)
df

输出

    day_of_week DOW
0   Monday       1
1   Tuesday      2
2   Wednesday    3
3   Monday       1

为了回答为什么你的代码不起作用,我仍在试图自己解决这个问题.

但是如果你换成以下两种方式之一,它似乎是可行的

df.iloc[i, <index location of 'DOW' column>] = value
df.loc[i]['DOW'] = value

工作,因为.iloc是基于整数的,而对于loc,您使用的标签现在与概述的一致.

但是,如果我只将if个语句中的一个更改为

inputData['DOW'] = ""

for i in range(0,len(inputData)):
#     print(inputData.iloc[i]['day_of_the_week'] == 'Monday')

    if 'Sunday' == inputData.iloc[i]['day_of_the_week']:
        inputData.iloc[i].DOW =1
        
    elif 'Monday' in inputData.iloc[i]['day_of_the_week']:
        inputData.loc[i]['DOW'] = 2
    elif 'Tuesday' in inputData.iloc[i]['day_of_the_week']:
       inputData.iloc[i].DOW=3
    elif 'Wednesday' in inputData.iloc[i]['day_of_the_week']:
       inputData.iloc[i].DOW=4
    elif 'Thursday' in inputData.iloc[i]['day_of_the_week']:
        inputData.iloc[i].DOW=5
    elif 'Friday' in inputData.iloc[i]['day_of_the_week']:
        inputData.iloc[i].DOW=6
    elif 'Saturday' in inputData.iloc[i]['day_of_the_week']:
        inputData.iloc[i].DOW =7

Python相关问答推荐

重置PD帧中的值

找到相对于列表索引的当前最大值列表""

如何在Python请求中组合多个适配器?

Python pint将1/华氏度转换为1/摄氏度°°

我对这个简单的异步者的例子有什么错误的理解吗?

使用Python TCP套接字发送整数并使用C#接收—接收正确数据时出错

合并相似列表

为什么我的scipy.optimize.minimize(method=";newton-cg";)函数停留在局部最大值上?

Python:在cmd中添加参数时的语法

Fake pathlib.使用pyfakefs的类变量中的路径'

在Python中使用unittest中的补丁进行动态模拟

设计添加和搜索词的数据 struct :Leetcode211

使用Python下载pdf url

用考克斯回归的生存分析系列的真值是模棱两可的.

极点:AWS S3连接池

Python渐进式打字

Django在两个领域进行连接

壁虎中的动态优化

设置gtuner计算机视觉时遇到问题

匹配+字符串的Python RegEx,直到找到下一个匹配项