【问题标题】:How do I split values in a column to various columns in a csv?如何将列中的值拆分为 csv 中的各个列?
【发布时间】:2022-11-28 09:42:51
【问题描述】:

我正在尝试将位置列中的值拆分为 csv 文件中的两个不同的 x 和 y 列

现在它看起来像这样:

location
[60.0, 56.0]    
[68.0, 74.0]    
[58.0, 52.0]
[63.0, 53.0]
[119.0, 79.0]

我希望它拆分列并获得两个不同的列并删除括号,以便列看起来像这样:

x           y
60          56
68          74
58          52
63          53
119         79

我所有这些: 1.

df[['x', 'y']] = pd.DataFrame(df['location'].tolist(), index=df.index)

pd.concat([df[[0]], df['location'].str.split(',', expand=True)], axis=1

df['location'].str.split(',', expand=True)

但是收到错误

【问题讨论】:

    标签: pandas pyspark cvs


    【解决方案1】:

    这是 pandas.read_fwfpandas.Series.str.split 的命题:

    df= (
          pd.read_fwf("name-path_of_your_csv.csv")
              ["location"].str.strip("[]")
                          .str.split(",", expand=True)
                          .rename(columns={0: "x", 1: "y"})
        )         
    

    # 输出 :

    print(df)
    
           x      y
    0   60.0   56.0
    1   68.0   74.0
    2   58.0   52.0
    3   63.0   53.0
    4  119.0   79.0
    

    【讨论】:

      【解决方案2】:

      这是另一种方法:

      df = pd.read_csv("name-path_of_your_csv.csv")
      

      然后将它们转换为所需的输出

      x = []
      y = []
      
      def splits(s):
        x.append(s[0])
        y.append(s[1])
      
      df['locations'].apply(splits)
      
      df['X'] = x
      df['Y'] = y
      
      # converting them to int
      df['X'].astype(int)
      df['Y'].astype(int)
      

      输出:

      【讨论】:

        猜你喜欢
        • 2019-02-03
        • 1970-01-01
        • 2018-02-18
        • 1970-01-01
        • 2018-05-17
        • 2022-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多