gpt4 book ai didi

python - python 拆分 pandas 列

转载 作者:太空宇宙 更新时间:2023-11-03 15:10:29 24 4
gpt4 key购买 nike

我正在研究 python 3.4,我有一个 pandas 数据框列,其中包含:

0    [0.3785766661167145, -0.449486643075943, -0.15...]
1 [0.204025000333786, -0.3685399889945984, 0.231...]
2 [0.684576690196991, -0.5823000073432922, 0.269...]
3 [-0.02300500124692917, -0.22056499123573303, 0...]
Name: comments, dtype: object

我想将其拆分并将其变成多个列:

   column1               column2              ...columnx
0 0.3785766661167145 -0.449486643075943 last element in the first list
1 0.204025000333786 -0.3685399889945984 last element in the 2nd list
2 0.684576690196991 -0.5823000073432922 last element in the 3rd list
3 -0.02300500124692917 -0.22056499123573303 last element in the 4th list

你能帮我一下吗?提前致谢

最佳答案

如果数据是列表,则需要DataFrame构造函数,通过values将列comments转换为numpy数组 + tolist :

print (type(df.loc[0, 'comments']))
<class 'list'>

df1 = pd.DataFrame(df['comments'].values.tolist())
#rename columns if necessary
df1 = df1.rename(columns = lambda x: 'column' + str(x + 1))
print (df1)
column1 column2 column3
0 0.378577 -0.449487 -0.150
1 0.204025 -0.368540 0.231
2 0.684577 -0.582300 0.269
3 -0.023005 -0.220565 0.000

关于python - python 拆分 pandas 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44239223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com