python - 用熊猫将行分成多行
问题描述
我有一个带有单列“数据”的数据框,其中包含用空格分隔的单词。我想将数据分成按空格分隔的多行。我尝试了以下代码但不起作用:
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)})
数据框示例
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
解决方案
您是否正在寻找这样的东西:
df = pd.DataFrame()
df['text'] = ['word1 word2 word3', 'hey there hello word', 'stackoverflow is amazing']
输入:
text
0 word1 word2 word3
1 hey there hello word
2 stackoverflow is amazing
做:
x = df.data.str.split(expand=True).stack().values
new_df = pd.DataFrame()
new_df['words'] = x.tolist()
输出:
words
0 word1
1 word2
2 word3
3 hey
4 there
5 hello
6 word
7 stackoverflow
8 is
9 amazing
推荐阅读
- java - Gremlin:从 edgeId 进出顶点,包括边缘属性
- python - 如何将对象传递给float ....ValueError:无法将字符串转换为float:''
- outlook-addin - 使用 ExecSQL 过滤日期时间
- java - 如何以独特的方式为减法中的补码分配变量
- android - 错误:[Dagger/DuplicateBindings] com.example.StartRouter 被绑定多次?
- java - 抽象类和私有方法
- java - Hibernate 抛出“NULL not allowed for column”,因为使用 @MapsId 时 SQL INSERT 中缺少 JPA OneToOne 关系 FK
- ansible - 接受用户输入并在多行中创建一个新文件
- rust - 从 rust 运行 LLC 会导致未定义对“main”的引用以与 gcc 链接
- oracle - PLSQL 触发器不工作 0 行插入