python-3.x - 重复创建行并替换单元格值

标签 python-3.x pandas

我有一个 CSV 文件,其中包含以下数据:

  NAME    | AGE  | COLLEGE  | BRANCH  | Qualification
------------------------------------------------------- 
  sai     | 21   |   FG     |   CSE   |   B.Tech
  Kiran   | 22   |   FG     |   EEE   |   M.Tech
  Anil    | 21   |   FG     |   CSE   |   B.Tech
  Ram     | 22   |   KL     |   EEE   |   B.Tech

我用来创建 CSV 文件的代码:

import pandas as pd

Name=['sai', 'Kiran', 'Anil', 'Ramj']
Age=[21, 22, 21, 22]
college=['FG', 'FG', 'FG', 'KL']
branch=['CSE', 'EEE', 'CSE', 'EEE']
Qualification=['B.Tech', 'M.Tech', 'B.Tech', 'B.Tech']

dict = {'NAME': Name, 'AGE': Age, 'COLLEGE': college, 'BRANCH': branch, 
'Qualification': Qualification }  

df = pd.DataFrame(dict) 
df.to_csv('TESTINGFILE.csv',index=False) 

需要实现以下步骤:


第 1 步:

根据条件,我需要创建一个重复行。

条件:COLLEGE = FG 且 BRANCH = CSE

如果满足条件,则应创建一个重复行,其分支名称为 ECE。

  NAME    | AGE  | COLLEGE  | BRANCH  | Qualification
------------------------------------------------------- 
  sai     | 21   |   FG     |   CSE   |   B.Tech
  sai     | 21   |   FG     |   ECE   |   B.Tech
  Kiran   | 22   |   FG     |   EEE   |   M.Tech
  Anil    | 21   |   FG     |   CSE   |   B.Tech
  Anil    | 21   |   FG     |   ECE   |   B.Tech
  Ram     | 22   |   KL     |   EEE   |   B.Tech

第 2 步:

现在具有相同的条件(COLLEGE = FG 和 BRANCH = CSE),如果满足,则将分支从 CSE 更改为 IT。

最终预期输出:

  NAME    | AGE  | COLLEGE  | BRANCH  | Qualification
------------------------------------------------------- 
  sai     | 21   |   FG     |   IT    |   B.Tech
  sai     | 21   |   FG     |   ECE   |   B.Tech
  Kiran   | 22   |   FG     |   EEE   |   M.Tech
  Anil    | 21   |   FG     |   IT    |   B.Tech
  Anil    | 21   |   FG     |   ECE   |   B.Tech
  Ram     | 22   |   KL     |   EEE   |   B.Tech

有人可以通过使用 pandas 编写代码来帮助我完成此操作吗?

感谢您的帮助!

最佳答案

首先按条件创建掩码,用掩码替换值,用concat重复行并通过 DataFrame.assign 赋值,最后DataFrame.sort_index :

mask = (df.COLLEGE == 'FG') & (df.BRANCH == 'CSE')
df.loc[mask, 'BRANCH'] = 'IT' 
df = pd.concat([df, df[mask].assign(BRANCH='ECE')]).sort_index().reset_index(drop=True)
print (df)
    NAME  AGE COLLEGE BRANCH Qualification
0    sai   21      FG     IT        B.Tech
1    sai   21      FG    ECE        B.Tech
2  Kiran   22      FG    EEE        M.Tech
3   Anil   21      FG     IT        B.Tech
4   Anil   21      FG    ECE        B.Tech
5   Ramj   22      KL    EEE        B.Tech

关于python-3.x - 重复创建行并替换单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55183413/

相关文章:

python - key 错误 : item not in index while trying to build boxplot with pandas

python - pandas.tslib.Timestamp 日期匹配

python - 基于过滤器的列计算?

列和行中的python pandas DataFrame子图

mysql - Python 字节到 geojson 点

python - 在 Mac 上用 Python 打开一个 txt 文件

python-3.x - 应用词形还原时出错

python - 删除 Pandas 数据框中每一行的标点符号

python mpl_toolkits 安装问题

python - 如何使用 Python 'in' 运算符检查我的列表/元组是否包含每个整数 0、1、2?