Skip to main content
 首页 » 编程设计

python之将字符串中的每个单词读入 pandas 新行

2025年05月04日20mq0036

我有以下字符串。 msg='国际货币基金组织总裁' 我想要像下面这样的 Pandas 数据框 ['这' '管理' '导演' '的' '这' '国际货币基金组织' ] 1 列和 6 行。

请您参考如下方法:

您可以使用 split使用 DataFrame 构造函数:

msg='The managing director of the IMF' 
df = pd.DataFrame(msg.split(), columns=['col']) 
print (df) 
        col 
0       The 
1  managing 
2  director 
3        of 
4       the 
5       IMF 

df = pd.DataFrame([msg.split()], columns=list('abcdef')) 
print (df) 
     a         b         c   d    e    f 
0  The  managing  director  of  the  IMF 

备选方案:

msg='The managing director of the IMF' 
L = msg.split() 
df = pd.DataFrame(np.array(L).reshape(-1, len(L)), columns=list('abcdef')) 
print (df) 
     a         b         c   d    e    f 
0  The  managing  director  of  the  IMF