python - 在 DataFrame Python 上同时迭代行和列的形式

标签 python python-3.x pandas

我有一个数据集,例如 df,其中包含以下信息。基本上我想迭代列并创建新列

df

ID Day1 Day2....Day10  

1  High  Low  

2  Medium High  

3  Low    Medium  

4  Low    Low  

5  High   High  

.   .      .  
.   .      .  
.   .      .  

现在,我想要以下输出:对于每一天到第 10 天,我想创建新列 标签 1 至标签 10。

ID Day1 Day2....Day10 Tag1 Tag2.......Tag10  

1  High  Low........  3     1        

2  Medium High        2     3

3  Low    Medium      1     2

4  Low    Low         1     1

5  High   Medium      3     2

.   .      .          .     .  
.   .      .          .     .
.   .      .          .     .  

我尝试过打击代码,但似乎不起作用

df1=df.reindex(columns=[*df.columns.tolist(),'Tag1','Tag2','Tag3','Tag4','Tag5','Tag6','Tag7','Tag8','Tag9','Tag10'],fill_value='NA')

days=['Tag1','Tag2','Tag3','Tag4','Tag5','Tag6','Tag7','Tag8','Tag9','Tag10']

for j in days:
    for i in range(df.shape[0]):
        if df[i]=='High':
            df[i,j]=1
        else:
            df[i,j]=0
    j+=1

最佳答案

使用DataFrame.filter对于 Day 列,则 DataFrame.replace ,更改列名称并通过 DataFrame.join 附加到原始内容:

d = {"Low": 1, "Medium": 2, "High": 3}
f = lambda x: x.replace('Day','Tag')
df = df.join(df.filter(like='Day').replace(d).rename(columns=f))
print (df)
   ID    Day1    Day2  Tag1  Tag2
0   1    High     Low     3     1
1   2  Medium    High     2     3
2   3     Low  Medium     1     2
3   4     Low     Low     1     1
4   5    High    High     3     3

关于python - 在 DataFrame Python 上同时迭代行和列的形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61093696/

相关文章:

python - Dataframe 对象中的拼写更正,Python

python - Pandas 在读取 SAS 文件时数据类型正确失败

python - 删除 UserProfile 时删除用户

python - 关于 'not callable' 的 PyCharm 警告

python - 为什么Python没有 "continue if"语句?

python - 同一列中的行元素对出现的次数

python - 如何使用新维度 reshape xarray 数据

python - heapq.heapify 不适用于子类列表

python - 套接字无法发送数据

python - pandas 数据透视数据框结构