[英]How to create new column using loop with condition
這是我的 DataFrame,我想使用帶條件的循環創建一個新列。
import pandas as pd
student_card = pd.DataFrame({'ID':[20190103, 20190222, 20190531],
'name':['Kim', 'Yang', 'Park'],
'class':['H', 'W', 'S']})
student_card['new'] = pd.Series() #1.create new column
for i, v in student_card['name'].items(): #2.set index and values
if "Yang" in v: #3.if there's "Yang" in value
student_card['new'].append(v) #4. append the value of name column in new coulum
所以我嘗試了這種方法並遇到以下錯誤:TypeError: cannot concatenate object of type '<class 'str'>'; 只有系列和 DataFrame objs 是有效的 順便說一句,這不是真的(此列的類型是系列)
append
所做的是連接一個系列,這在您的代碼中不是這種情況,因為v
是一個字符串, i
是該字符串的索引。 您可以嘗試打印print(type(v))
並親自查看。 至於文檔,你可以在這里找到它: https://pandas.pydata.org/docs/reference/api/pandas.Series.append.ZFC35FDC70D5FC69D2698Z83A822C7A5E
您正在尋找的是為列上的現有索引設置一個值(或在熊貓中稱為系列)。 像這樣的東西:
df.loc[index] = value
所以在你的代碼中,這應該可以解決問題
import pandas as pd
student_card = pd.DataFrame({'ID':[20190103, 20190222, 20190531],
'name':['Kim', 'Yang', 'Park'],
'class':['H', 'W', 'S']})
student_card['new'] = pd.Series() #1.create new column
for i, v in student_card['name'].items(): #2.set index and values
if "Yang" in v: #3.if there's "Yang" in value
student_card['new'].loc[i] = v #4. append the value of name column in new coulum
Append將連接兩個系列。 你想要的是訪問一行。 使用iloc 或 iat 之類的索引來執行此操作:
import pandas as pd
student_card = pd.DataFrame({'ID':[20190103, 20190222, 20190531],
'name':['Kim', 'Yang', 'Park'],
'class':['H', 'W', 'S']})
student_card['new'] = pd.Series() #1.create new column
for i, v in student_card['name'].items(): #2.set index and values
if "Yang" in v: #3.if there's "Yang" in value
student_card['new'].iat[i] = v #4. append the value of name column in new coulum
Output:
(指數) | ID | 姓名 | class | 新的 |
---|---|---|---|---|
0 | 20190103 | 金 | H | 鈉 |
1 | 20190222 | 楊 | W | 楊 |
2 | 20190531 | 公園 | 小號 | 鈉 |
您真的不應該使用循環來操作 pandas dataframe,這是一種反模式。
此外,現在不推薦使用append
。
使用帶有boolean 索引的矢量方法:
# select the rows for which name==Yang and add the same name in the new column
student_card.loc[student_card['name'].eq('Yang'), 'new'] = student_card['name']
或者,使用where
:
# mask all non matching values (name!=Yang) and copy the column
student_card['new'] = student_card['name'].where(student_card['name'].eq('Yang'))
output:
ID name class new
0 20190103 Kim H NaN
1 20190222 Yang W Yang
2 20190531 Park S NaN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.