python - 根据列值复制行
问题描述
我有一个df
可以在列类型中有 6 个不同输入的 a:3 个输入是string
,word
另外something
3 个输入其名称,s
最后是 a:
types Value File Number
0 string Old dat 1.0
1 word Old dat 2.0
2 something Old dat 3.0
3 somethings Old dat 4.0
4 words Old dat 5.0
我想得到一个 我只复制在列类型中最后df
没有对应的行。s
并添加str(New)
到列值。
输出:
types Value File Number
0 string Old dat 1.0
1 word Old dat 2.0
2 something Old dat 3.0
3 somethings Old dat 4.0
4 words Old dat 5.0
5 string New dat 1.0
解决方案
您可以执行以下操作:
def insert_rows(df):
types = df["types"].values
unique_without_s = [t for t in types if t[-1] != 's']
unique_with_s = [w for w in unique_without_s if f"{w}s" in types]
diff = [w for w in unique_without_s if w not in unique_with_s]
new_df = df.copy()
for _, row in df.iterrows():
if row.types in diff:
new_df = new_df.append({"types": row['types'], "Value": 'New',
"File": row['File'], "Number": row['Number']}, ignore_index=True)
return new_df
推荐阅读
- python - 'ManyToManyDescriptor' 对象在带有 PostgreSQL 的 Django 中没有属性 'add'
- reactjs - 如何在react.js中的recharts条形图中等间距(包括开始和结束)
- python - 每次for循环后如何清除jupyter笔记本单元格中的输出?
- kubernetes - Kubernetes:envFrom 何时从 ConfigMap 导入值?
- javascript - 如何在移动视图中修复页脚上的空白
- python - 如何检查字典中的列表值是否相等?
- node.js - ExpressJS:如何按需缓存
- url - 如何在LWC社区页面中形成一个可以携带用户信息的URL?
- javascript - 将回调转换为 async/await 函数
- reactjs - 我不知道如何使用类修复 useSprint