我有一个清单:
mylist=["one","two","three","slgrmff","signaff","huslness"]
和数据框:
busy quicksilver sign
0 huslness qulzkslwx slgrmff
1 NaN NaN signaff
我正在尝试使用数据框中的列名替换mylist中的项目,如果该列包含该项目。
我的预期输出是:["one","two","three","sign","sign","busy"]
答案 0 :(得分:2)
试试这个:
for (i,item) in enumerate(mylist):
for col in df.columns:
if item in df[col].tolist():
mylist[i]=col
我确信他们有更多的pythonic方法,但这可以做到这一点!
答案 1 :(得分:2)
一种方法是使用字典。这可能比每次循环数据帧并与列表进行比较更有效。
d = {}
for col in df:
d.update(dict.fromkeys(df[col].dropna().unique(), col))
mylist=["one","two","three","slgrmff","signaff","huslness"]
res = [d.get(i, i) for i in mylist]
# ['one', 'two', 'three', 'sign', 'sign', 'busy']