![](/img/trans.png)
[英]Using python how to take input search string from one excel sheet column and search in other excel on a specific column?
[英]How to take two specific words from an Excel sheet and add them to another column with Python
我是 Python 的新手,正在做一個項目,我需要清理我的數據。
我想添加一個只有“IN”或“OUT”字樣的新列。
import pandas as pd
df = pd.read_excel("tourniquets_26.07.2022_test.xls") #Read Excel as file as Dataframe
#My try to use a loop to find it
for word in df["Deur intelligente eenheid"]:
if word == "IN" or word == "UIT":
df['IN/UIT'] = word
#Display top 5 rows
print(df.head(5))
#To save it back as Excel
df.to_excel("tourniquets_26.07.2022_test.xls") #Write DataFrame back as Excel file
先感謝您
據我了解,邏輯是您當前df中的列總是(其中某處)單詞“IN”我們的“UIT”,並且您想要一個只有相應“IN”或“ UIT”這個詞,對吧?
如果是這樣,您可以使用Series.apply
來執行此操作。 創建一個 function 根據句子中的單詞返回“IN”或“UIT”:
def my_fun(sentence):
if "IN" in sentence:
return "IN"
else: #assuming that if it doesn't contain "IN", it must contain "UIT"
return "UIT"
並將其應用於 df["col_1"] 以創建一個新列。 假設您的列名為“col_1”:
df['IN/UIT'] = df["col_1"].apply(my_fun)
您可以使用 np.where:
import numpy as np
df['IN/UIT'] = np.where(df['col'].str.startswith('IN'), 'IN', 'UIT')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.