【发布时间】:2020-02-18 09:49:13
【问题描述】:
我正在使用一段代码,它应该读取每行数据中的列,并根据该单元格的值创建一个文件名来选择。我被要求使用 if elif else 语句,但代码有时会选择正确的值,有时不会。所以,
这是数据样本:
S.No File refrence Time Detection_Location
1 5008_P1_272 2019-04-24 16:15:53 CV22
2 5007_P2_467 2019-04-25 19:00:22 CV23
我用于此操作的代码是:
# Converting columns to datetime format
df['Time'] = pd.to_datetime(df['Time'], errors = 'coerce').dt.date
#Stripping the datetime
df['Time'] = pd.to_datetime(df['Time'])
df['Time'] = df['Time'].dt.strftime('%Y-%m-%d')
df[['Stripped Year', 'Stripped Month','Strip date']] = df['Time'].str.split(pat = "-", n=2, expand = True)
# Creating the file name string
for i in df.index:
First = 'PHD'
#for s in df['Stripped Year']:
s = df.iloc[i]['Stripped Year']
second1 = s[2:]
print(second1)
s1 = df.iloc[i]['Stripped Month']
second2 = s1
print(second2)
if second2 == '02':
second3 = '28'
if second2 == '01' or '03' or '05' or '07' or '08' or '10' or '12':
second3 = '31'
if second2 == '04' or '06' or '09' or '11':
second3 = '30'
print(second3)
s2 = df.iloc[i]['Detection_Location']
if s2 == 'CV22':
second4 = 'L1'
elif s2 == 'CV23':
second4 = 'L2'
elif s2 == 'CV3':
second4 = 'LC'
print(second4)
PHD_File_Name = First + ' ' +second1+second2+'01' + ' ' +second1+second2+second3 + ' ' + second4 + '_transformed' + '.xlsx'
print(PHD_File_Name)
我的代码有时在选择月份值(从 second2 值中选择 second3 值)时似乎运行良好,有时它没有选择正确的月份。我使用了 if elif else 和 if else else 语句,但代码的性能并不一致。请帮助我做错了什么。
第一行数据的期望输出应该是:
second1 = 2019
second2 = 04
second3 = 30
谢谢
【问题讨论】:
-
您可以使用
isin()来检查或条件。试试second2.isin(['01' ,'03' ,'05' ,'07' ,'08' ,'10' ,'12'])这是一个例子df = pd.Series([10, 25, 3, 25, 24, 6])' This will give true if one item is in the seriesany(df.isin([10,3]))` -
小心,这似乎真的很单调。你读过 Pandas 文档吗?你为什么要
df['Time'] = pd.to_datetime(df['Time'], errors = 'coerce').dt.date; df['Time'] = pd.to_datetime(df['Time']); df['Time'] = df['Time'].dt.strftime('%Y-%m-%d')?df[['Stripped Year', 'Stripped Month','Strip date']] = df['Time'].str.split(pat = "-", n=2, expand = True)可能是不必要的,有一些方法可以获取日期的特定元素。 -
@AMC - 不,我是使用熊猫的新手。我只是在尝试使我的代码健壮并正常工作。不确定一些事情是否不重要。可能是。
-
不确定一些事情是否不重要。可能是。我不确定我明白你的意思,你能详细说明一下吗?
标签: python python-3.x pandas dataframe if-statement