![](/img/trans.png)
[英]Pandas: creating a new column with “Yes” in case a pre-existing column contains some value and “No” if the value of the column is ' '
[英]Creating another column in pandas based on a pre-existing column
我的數據框中有第三列,我希望能夠創建看起來幾乎相同的第四列,除了它沒有雙引號並且列表中的每個 ID 之前都有一個“用戶/”前綴。 此外,有時它只是一個 ID 與 ID 列表(如示例 DF 所示)。
原來的
col1 col2 col3
01 01 "ID278, ID289"
02 02 "ID275"
想要的
col1 col2 col3 col4
01 01 "ID278, ID289" user/ID278, user/ID289
02 02 "ID275" user/ID275
鑒於:
col1 col2 col3
0 1.0 1.0 "ID278, ID289"
1 2.0 2.0 "ID275"
2 2.0 1.0 NaN
正在做:
df['col4'] = (df.col3.str.strip('"') # Remove " from both ends.
.str.split(', ') # Split into lists on ', '.
.apply(lambda x: ['user/' + i for i in x if i] # Apply this list comprehension,
if isinstance(x, list) # If it's a list.
else x)
.str.join(', ')) # Join them back together.
print(df)
輸出:
col1 col2 col3 col4
0 1.0 1.0 "ID278, ID289" user/ID278, user/ID289
1 2.0 2.0 "ID275" user/ID275
2 2.0 1.0 NaN NaN
df.col4 = df.col3.str.strip('"')
df.col4 = 'user/' + df.col4
應該做的伎倆。
通常,向量化字符串操作的操作由pd.Series.str...
操作執行。 它們的大多數名稱都與 Python 字符串方法或re
方法非常匹配。 Pandas 通常支持帶有字符串的標准 Python 運算符(+、-、* 等),並將標量作為向量與您正在使用的列的維度進行插值。
一個緩慢的選擇總是只使用Series.apply(func)
,它只是迭代系列中的值並將值傳遞給函數func
。
您可以使用 .apply() 功能:
def function(x):
if not x:
return ""
elements = x.split(", ")
out = list()
for i in elements:
out.append(f"user/{i}")
return ", ".join(out)
df["col4"] = df.col3.apply(function)
返回:
col1 col2 col3 col4
1 1 ID278, ID289 user/ID278, user/ID289
2 2 ID275 user/ID275
3 3
這是一個同時考慮雙引號和 ID 列表的解決方案:
# remove the double quotes
df['col4'] = df['col3'].str.strip('"')
# split the string, add prefix user/, and then join
df['col4'] = df['col4'].apply(lambda x: ', '.join(f"user/{userId}" for userId in x.split(', ')))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.