【问题标题】:Data frame multiple columns splitting数据框多列拆分
【发布时间】:2020-06-03 04:17:28
【问题描述】:

我有一个以下格式的熊猫数据框。

0     06-10-2000 Deposit $40.00
1  09-12-2002 Withdraw $1000.00
2     27-06-2001 Deposit $47.00
3   07-12-2021 Withdraw $100.00
4    06-10-2022 Deposit $120.00
5     06-10-2000 Deposit $40.00
6    09-12-2024 Withdraw $50.00

如何将每一行分成 3 列。 想要的理想输出:

      Date       Status   Amount
0     06-10-2000 Deposit $40.00
1  09-12-2002 Withdraw $1000.00
2     27-06-2001 Deposit $47.00
3   07-12-2021 Withdraw $100.00
4    06-10-2022 Deposit $120.00
5     06-10-2000 Deposit $40.00
6    09-12-2024 Withdraw $50.00

【问题讨论】:

  • 读取 CSV 文件时使用 pd.read_csv(your_file, sep='\s+', engine='python')
  • s.str.split(expand=True)?

标签: python pandas


【解决方案1】:

您可以使用命名组和extract

df[1].str.extract('(?P<Date>.*) (?P<Status>.*) (?P<Amount>.*)')

输出:

         Date    Status    Amount
0  06-10-2000   Deposit    $40.00
1  09-12-2002  Withdraw  $1000.00
2  27-06-2001   Deposit    $47.00
3  07-12-2021  Withdraw   $100.00
4  06-10-2022   Deposit   $120.00
5  06-10-2000   Deposit    $40.00
6  09-12-2024  Withdraw    $50.00

【讨论】:

    【解决方案2】:

    假设列中的分隔符是whitespace,您可以使用str.splitexpand=True

    df[['col1','col2','col3']] = df['column'].str.split(expand=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 2013-08-04
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多