【问题标题】:How can I split a column into 2 in the correct way in Python?如何在 Python 中以正确的方式将一列拆分为 2?
【发布时间】:2018-03-13 11:05:59
【问题描述】:

我正在从网站上抓取表格,并将其放入 Excel 文件。我的目标是以正确的方式将一列分成两列。

我要拆分的列:“STATUS”

我想要这个表格:

第一个示例:预计下午 3:17 --> 预计下午 3:17

第二个例子:延迟 3:00 PM --> 延迟和 3:00 PM

第三个例子:Canceled --> Canceled and (empty cell)

所以,我需要分隔第一个单词(在第一列中),然后是下一个字符。

我该怎么做?

这里是我的相关代码,里面已经包含了格式化代码。

df2 = pd.DataFrame(datatable,columns = cols)
df2['a'] = df2['FLIGHT'].str[:2]
df2['b'] = df2['FLIGHT'].str[2:].str.zfill(4)
df2["UPLOAD_TIME"] = datetime.now()
mask = np.column_stack([df2[col].astype(str).str.contains(r"Scheduled", na=True) for col in df2])
df3 = df2.loc[~mask.any(axis=1)] 

if os.path.isfile("output.csv"):
    df1 = pd.read_csv("output.csv", sep=";")
    df4 = pd.concat([df1,df3])
    df4.to_csv("output.csv", index=False, sep=";")

else:
    df3.to_csv
    df3.to_csv("output.csv", index=False, sep=";")

这里是我表中的 excel prt sc:

【问题讨论】:

标签: python pandas dataframe split debian


【解决方案1】:

您可以使用str.split - n=1 按第一个空格分割,expand=True 用于返回DataFrame,可以分配给新列:

df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)

示例:

df2 = pd.DataFrame({'STATUS':['Estimated 3:17 PM','Delayed 3:00 PM']})


df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)
print (df2)
              STATUS          c        d
0  Estimated 3:17 PM  Estimated  3:17 PM
1    Delayed 3:00 PM    Delayed  3:00 PM

如果输入中没有空格,则在输出中得到None

df2 = pd.DataFrame({'STATUS':['Estimated 3:17 PM','Delayed 3:00 PM', 'Canceled']})


df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)
print (df2)
              STATUS          c        d
0  Estimated 3:17 PM  Estimated  3:17 PM
1    Delayed 3:00 PM    Delayed  3:00 PM
2           Canceled   Canceled     None

如果需要将None 替换为空字符串,请使用fillna:

df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)
df2['d'] = df2['d'].fillna('')
print (df2)
              STATUS          c        d
0  Estimated 3:17 PM  Estimated  3:17 PM
1    Delayed 3:00 PM    Delayed  3:00 PM
2           Canceled   Canceled         

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 2019-11-24
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 2017-09-12
    • 1970-01-01
    • 2013-03-06
    相关资源
    最近更新 更多