【发布时间】:2021-11-21 16:42:35
【问题描述】:
我有一个看起来像这样的 DataFrame...
Variable
0 Religion - Buddhism
1 Source: Clickerz
2 Religion - Islam
3 Source: SRZ FREE
4 Ethnicity - Mixed - White & Black African
我想操纵variable列来创建一个看起来像这样的new column...
Variable New Column
0 Religion - Buddhism Buddhism
1 Source: Clickerz Clickerz
2 Religion - Islam Islam
3 Source: SRZ FREE SRZ FREE
4 Ethnicity - Mixed - White & Black African Mixed - White and Black African
这样我最终可以拥有一个看起来像这样的 DataFrame...
Variable New Column
0 Religion Buddhism
1 Source Clickerz
2 Religion Islam
3 Source SRZ FREE
4 Ethnicity Mixed - White and Black African
我想遍历Variable 列并操作数据以创建New Column。我计划使用多个 if 语句来查找特定单词,例如 'Ethnicity' 或 'Religion',然后应用操作。
例如...
For row in df['Variable']:
if 'Religion' in row:
df['New Column'] = ...
elif 'Ethnicity' in row:
df['New Column'] = ...
elif: 'Source' in row:
df['New Column'] = ...
else:
df['New Column'] = 'Not Applicable'
尽管type(row) 返回'str' 表示它属于类字符串,但此代码仍将新列全部返回为“不适用”,这意味着它未检测到数据中任何行中的任何字符串即使我可以看到它们在那里,也可以框架。
我确信有一种简单的方法可以做到这一点...请帮助!
我也尝试了以下...
For row in df['Variable']:
if row.find('Religion') != -1:
df['New Column'] = ...
elif row.find('Ethnicity') != -1:
df['New Column'] = ...
elif: row.find('Source') != -1:
df['New Column'] = ...
else:
df['New Column'] = 'Not Applicable'
我继续将新列的所有条目都设为“不适用”。再次在现有列中找不到字符串。
是数据类型的问题还是什么?
【问题讨论】:
标签: python pandas dataframe for-loop if-statement