使用字符值在 Pandas 中创建新行
Using character value to create new rows in Pandas
我需要根据特定列中出现的值在 pandas
数据框中创建新行。
创建拆分的模式是有一个分号指示我需要在何处开始新行。
df
animal cat;dog;cat
animal dog
animal fish
color black;green
color red
desired_df
animal cat
animal dog
animal cat
animal dog
animal fish
color black
color green
color red
我见过使用 pandas split 创建新列或行的解决方案,使用 df 中的给定字符或值(例如 : and : ), however, I have not seen a solution that does this with text values. I have also seen solutions (as well as one that I requested myself )能够准确地填充空值pandas 中的值。但是,我需要将这两种技术结合起来,我不清楚这在单行(或两行)中是否可行。
In [200]: df
Out[200]:
col1 col2
0 animal cat;dog;cat
1 animal dog
2 animal fish
3 color black;green
4 color red
In [201]: (df.set_index('col1')
.col2.str.split(';', expand=True)
.stack()
.reset_index(level=1, drop=True)
.reset_index(name='col2'))
Out[201]:
col1 col2
0 animal cat
1 animal dog
2 animal cat
3 animal dog
4 animal fish
5 color black
6 color green
7 color red
使用 numpy.repeat
和 itertools.chain
:
import numpy as np
from itertools import chain
split = df['col2'].str.split(';')
res = pd.DataFrame({'col1': np.repeat(df['col1'], split.map(len)),
'col2': list(chain.from_iterable(split))})
print(res)
col1 col2
0 animal cat
0 animal dog
0 animal cat
1 animal dog
2 animal fish
3 color black
3 color green
4 color red
我需要根据特定列中出现的值在 pandas
数据框中创建新行。
创建拆分的模式是有一个分号指示我需要在何处开始新行。
df
animal cat;dog;cat
animal dog
animal fish
color black;green
color red
desired_df
animal cat
animal dog
animal cat
animal dog
animal fish
color black
color green
color red
我见过使用 pandas split 创建新列或行的解决方案,使用 df 中的给定字符或值(例如
In [200]: df
Out[200]:
col1 col2
0 animal cat;dog;cat
1 animal dog
2 animal fish
3 color black;green
4 color red
In [201]: (df.set_index('col1')
.col2.str.split(';', expand=True)
.stack()
.reset_index(level=1, drop=True)
.reset_index(name='col2'))
Out[201]:
col1 col2
0 animal cat
1 animal dog
2 animal cat
3 animal dog
4 animal fish
5 color black
6 color green
7 color red
使用 numpy.repeat
和 itertools.chain
:
import numpy as np
from itertools import chain
split = df['col2'].str.split(';')
res = pd.DataFrame({'col1': np.repeat(df['col1'], split.map(len)),
'col2': list(chain.from_iterable(split))})
print(res)
col1 col2
0 animal cat
0 animal dog
0 animal cat
1 animal dog
2 animal fish
3 color black
3 color green
4 color red