python - Pandas 将列中的字符串拆分为多条记录

标签 python pandas

我有一个数据框 df

col1   col2  col3
a;b;c  w;x     1
d;e;f  x;y     2
g;h;i  z;u;v   3

我想将 col1col2 列中的每个字符串拆分为单独的记录,以便数据框看起来像这样

col1    col2    col3
a       w       1
b       x       1
c       NaN     1
d       x       2
e       y       2
f       NaN     2
g       z       3
h       u       3
i       v       3

最佳答案

尝试组合 Series.str.split , Series.stack , Series.rename , pandas.concat , DataFrame.assignDataFrame.reset_index像这样:

例子

df = pd.DataFrame([{'col1': 'a;b;c', 'col2': 'w;x', 'col3': 1}, {'col1': 'd;e;f', 'col2': 'x;y', 'col3': 2}, {'col1': 'g;h;i', 'col2': 'z;u;v', 'col3': 3}, {'col1': '1,2,3', 'col2': '2', 'col3': 4}])

print(df)

#     col1   col2  col3
# 0  a;b;c    w;x     1
# 1  d;e;f    x;y     2
# 2  g;h;i  z;u;v     3
# 3  1,2,3      2     4

df_new = (pd.concat([df[x].str.split('[;,]', expand=True).stack().rename(x)
                     for x in df[['col1', 'col2']]], axis=1)
          .reset_index(level=1, drop=True)
          .assign(col3=df.col3))

print(df_new)

  col1 col2  col3
0    a    w     1
0    b    x     1
0    c  NaN     1
1    d    x     2
1    e    y     2
1    f  NaN     2
2    g    z     3
2    h    u     3
2    i    v     3
3    1    2     4
3    2  NaN     4
3    3  NaN     4

关于python - Pandas 将列中的字符串拆分为多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713309/

相关文章:

python - Pandas dataframe 应用引用前一行来计算差异

python pandas多索引选择满足条件的索引级别内的所有内容

python - 使用 for 循环更改列表中的值 (python)

python - len() 与 arange() 的行为

python - 如何使用 spacy nlp 查找专有名词

Python Selenium - 无法点击按钮

python - Pylab 用表格绘图

Pandas 返回包含字符串的单元格位置

python - Python Coverage .coveragerc 文件在哪里?

python - colorbar matplotlib python 上的 onclick 方法