Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用分隔符将一列拆分为三列_Python_Pandas - Fatal编程技术网

Python 使用分隔符将一列拆分为三列

Python 使用分隔符将一列拆分为三列,python,pandas,Python,Pandas,回到另一个问题。最近,我在我的企业中获取了员工出勤率的置信区间,并将结果转换为数据框架: def mean_confidence_interval(unstacked, confidence=0.9): a = 1.0 * np.array(unstacked) n = len(a) m, se = np.nanmean(a), scipy.stats.sem(a, nan_policy='omit') h = se * scipy.stats.t.ppf((1

回到另一个问题。最近,我在我的企业中获取了员工出勤率的置信区间,并将结果转换为数据框架:

def mean_confidence_interval(unstacked, confidence=0.9):
    a = 1.0 * np.array(unstacked)
    n = len(a)
    m, se = np.nanmean(a), scipy.stats.sem(a, nan_policy='omit')
    h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
    return m, m-h, m+h

answer = unstacked.apply(mean_confidence_interval)
answer = answer.to_frame(name='Interval')
answer = answer.reset_index()
answer
输出与此类似的内容

Employee|             Interval
-------------------------------
Karl    |      (0.75,0.70,0.80)
我一直在尝试使用逗号作为分隔符来创建三个新列

Mean | Low | High
到目前为止,我试过:

answer[['Mean','Low', 'High']] = answer['Interval'].str.split(',',expand=True)
answer
只需将其与以下内容一起返回:

ValueError: Columns must be same length as key
我还尝试使用
str.extract
如下所示:

p = r'(?P<Mean>-?\d+\.\d+).*?(?P<Low>-?\d+\.\d+).*?(?P<High>-?\d+\.\d+)'
answer[['Mean','Low', 'High']] = answer['Interval'].str.extract(p,expand=True)
answer

有人知道我做错了什么吗?

这是
tuple
不是string

pd.DataFrame(df.Interval.values.tolist())
Out[1098]: 
      0    1    2
0  0.75  0.7  0.8

#df[['Mean','Low', 'High']]=pd.DataFrame(df.Interval.values.tolist())
将数据类型更改为
str
后,您的正则表达式将工作

df['Interval'].astype(str).str.extract(p,expand=True)
Out[1103]: 
   Mean  Low High
0  0.75  0.7  0.8

这是元组,而不是字符串

pd.DataFrame(df.Interval.values.tolist())
Out[1098]: 
      0    1    2
0  0.75  0.7  0.8

#df[['Mean','Low', 'High']]=pd.DataFrame(df.Interval.values.tolist())
将数据类型更改为
str
后,您的正则表达式将工作

df['Interval'].astype(str).str.extract(p,expand=True)
Out[1103]: 
   Mean  Low High
0  0.75  0.7  0.8

我猜你有一列元组
(0.75,0.70,0.80)
,而不是字符串
'(0.75,0.70,0.80)
。也许可以试试
answer[['Mean','Low','High']]=answer.Interval.apply(pd.Series)
的效果非常好!很高兴它成功了!但是使用@Wen的解决方案,Series.apply是没有效率的。我猜你有一列元组
(0.75,0.70,0.80)
,而不是字符串
'(0.75,0.70,0.80)
。也许可以试试
answer[['Mean','Low','High']]=answer.Interval.apply(pd.Series)
的效果非常好!很高兴它成功了!但是使用@Wen的解决方案,Series.apply是没有效率的。