简体   繁体   English

用熊猫将行拆分为多行

[英]Split row into multiple rows with pandas

I have a data frame with a single column 'data' which contains words separated by space. 我有一个带有单列“ data”的数据框,其中包含以空格分隔的单词。 I want to separate the data into multiple rows split by space. 我想将数据分成多行,并按空格分开。 I have tried the following code but does not work: 我已经尝试了以下代码,但是不起作用:

from itertools import chain
def chainer(s):
    return list(chain.from_iterable(s.str.split('\s+')))  
lengths = df['data'].str.split('\s+').map(len)
df_m = pd.DataFrame({"data" : np.repeat(df["data"], lengths)})

Dataframe example 数据框示例

words = ["a b c d e","b m g f e","c" ,"w"]
dff = pd.DataFrame({"data" :words })


data
0   a b c d e
1   b m g f e
2   c
3   w

Are you looking for something like this: 您是否正在寻找这样的东西:

df = pd.DataFrame()
df['text'] = ['word1 word2 word3', 'hey there hello word', 'stackoverflow is amazing']

Input: 输入:

                       text
0         word1 word2 word3
1      hey there hello word
2  stackoverflow is amazing

Do: 做:

x = df.data.str.split(expand=True).stack().values
new_df = pd.DataFrame()
new_df['words'] = x.tolist()

Output: 输出:

           words
0          word1
1          word2
2          word3
3            hey
4          there
5          hello
6           word
7  stackoverflow
8             is
9        amazing

Below is my attempt. 以下是我的尝试。

words = ['oneword','word1 word2 word3', 'hey there hello word', 'stackoverflow is amazing']
# make list of list and flatten.
flat_list = [item for sublist in words for item in sublist.split(' ')]
# put flat_list into DataFrame.
df = pd.DataFrame({"data" :flat_list })
print(df)

             data
0         oneword
1           word1
2           word2
3           word3
4             hey
5           there
6           hello
7            word
8   stackoverflow
9              is
10        amazing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM