我有以下示例数据帧和列表(从 df 中提取)。
import pandas as pd
color_list = ['green','blue','red','yellow','black']
df = pd.DataFrame({'object': ['car','plane','tree','house','phone'],
'colors': ['red, blue',
'red, yellow, black',
'black',
'green, blue',
'yellow, green, blue']})
我设法创建了一个 for 循环,可以正确检查颜色列中是否存在某种颜色(来自 color_list)。然后,它创建一个新列来评估该条件并将 True 或 False 分配给每一行。代码如下:
idx = df.columns.get_loc('colors') + 1
for i in range(len(color_list)):
df.insert(loc= idx + i,
column='has ' + color_list[i],
value = (df['colors'].str.contains(color_list[i], case=False, na=False)))
它输出以下内容:
object colors has green ... has red has yellow has black
0 car red, blue False ... True False False
1 plane red, yellow, black False ... True True True
2 tree black False ... False False True
3 house green, blue True ... False False False
4 phone yellow, green, blue True ... False True False
哪个是正确的,问题是我可以将条件传递给 pd.insert 的值参数吗?
我想将 True 值替换为“has”+(列名称)”,将 False 替换为“没有”+(列名称)之类的值。这可以在同一个循环中完成吗?
谢谢
最佳答案
根据documentation ,pandas.DataFrame.insert方法没有这个功能。
您可以使用 pandas.DataFrame.apply 来执行此操作。
for color in color_list:
col_name = 'has ' + color
df[col_name] = df['colors'].apply(lambda x: f'has {color}' if color in x else f'doesn\'t have {color}')
关于python - 在 Pandas DataFrame 中插入新列和相应的值(根据条件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61330128/