JavaEar 专注于收集分享传播有价值的技术资料

Split a column into multiple columns in Pandas

data={'GradeCol':['BVCS,105308.248']}

data1=DataFrame(data)
print(data1)
data1[['GradeColText','GradeColNum']] = pd.DataFrame([x for x in 
data1.GradeCol])

#data1[['GradeColText','GradeColNum']] = 
#pd.DataFrame(data1.GradeCol.values.tolist())
print(data1)

while splitting row into columns getting error ValueError: Columns must be same length as key

Expected output

GradeColText GradeColNum

BVCS         105308.248

2个回答

    最佳答案
  1. Try this ?

    data={'GradeCol':['BVCS,105308.248']}
    df=pd.DataFrame(data)
    df = pd.DataFrame(df.GradeCol.str.split(',', 1).tolist(),
                      columns=['GradeColText', 'GradeColNum'])
    
      GradeColText GradeColNum
    0         BVCS  105308.248
    
  2. 参考答案2
  3. You can use df.str.rsplit(expand=True):

    In [429]: df[['GradeColText', 'GradeColNum']] = df['GradeCol'].str.rsplit(',', expand=True)
    
    In [432]: df.drop(['GradeCol'], axis=1, inplace=True); df
    Out[432]: 
      GradeColText GradeColNum
    0         BVCS  105308.248