如何处理多个"if"语句?
这是我的代码:
# Read the CSV file into a pandas dataframe
df = pd.read_csv(csv_file, sep='|', header=0)
for col in df.columns:
#Check if the word "date" is in the column name
if "date" in col.lower():
# Convert the column to a datetime type
df[col] = pd.to_datetime(df[col])
elif "payment_tier_number" in col.lower():
# Convert the column to a float type
df[col] = df[col].astype(float/decimal???)
elif "number" in col.lower():
# Convert the column to an int type
df[col] = df[col].astype(int)
else:
# Convert the column to a string type
df[col] = df[col].astype(str)
我不太确定我在这里使用 elif
和 else
的方式是否正确。我想把那些列名中包含“date”的数据类型转换成“datetime”,如果列名是“payment_tier_number”,那么就把它变成小数;如果列名中有“number”,就把它变成“int”类型,其他的就用字符串类型。我能让一个 if
语句正常工作,但对于多个语句我有点困惑。
1 个回答
0
你使用的if条件看起来不错。不过在“payment_tier_number”这一行的列转换上有一点小问题。我觉得这里应该用float,而不是float/decimal。
df[col] = df[col].astype(float)