我对python非常陌生。我遇到了这项任务,并在没有任何线索的情况下执行了一段时间。 任何建议都有帮助!非常感谢
我有这样一个数据框:
import pandas as pd
data = {'A': ['Emo/3', 'Emo/4', 'Emo/1','Emo/3', '','Emo/3', 'Emo/4', 'Emo/1','Emo/3', '', 'Neu/5', 'Neu/2','Neu/5', 'Neu/2'],
'Pos': ["repeat3", "repeat3", "repeat3", "repeat3", '',"repeat1", "repeat1", "repeat1", "repeat1", '', "repeat2", "repeat2","repeat2", "repeat2"],
}
df = pd.DataFrame(data)
df
A Pos
0 Emo/3 repeat3
1 Emo/4 repeat3
2 Emo/1 repeat3
3 Emo/3 repeat3
4
5 Emo/3 repeat1
6 Emo/4 repeat1
7 Emo/1 repeat1
8 Emo/3 repeat1
9
10 Neu/5 repeat2
11 Neu/2 repeat2
12 Neu/5 repeat2
13 Neu/2 repeat2
我想要这样的输出:
A Pos B
0 Emo/3 repeat3 0
1 Emo/4 repeat3 0
2 Emo/1 repeat3 0
3 Emo/3 repeat3 0
4
5 Emo/3 repeat1 1
6 Emo/4 repeat1 2
7 Emo/1 repeat1 3
8 Emo/3 repeat1 4
9
10 Neu/5 repeat2 4
11 Neu/2 repeat2 2
12 Neu/5 repeat2 3
13 Neu/2 repeat2 1
列“B”的前四个位置始终为0。然后,“B”列中的其他位置基于“pos”列中的值。如果“pos”列中的行等于“repeat 1”,则该四个位置的“B”列将为:1、2、3、4。如果“位置”列中的行等于“重复2”,则四个位置的“B”列将为:4、3、2、1
Pos中的值始终按每四行相同的值排列,第五行为空
非常感谢
这是一种使用内置计数器和掩码的完全矢量化方法(步骤将在下一节中详细说明):
输出:
步骤
使用^{} 从空行分隔符创建伪组:
使用^{} 创建节内计数器:
使用^{} 屏蔽除
repeat1
行之外的所有内容:对于} 掩盖所有其他内容:
repeat2
行,将计数器从01234->;43210(减去5并取绝对值),然后再次使用^{所以现在} 将所有
B
列是rep1 + rep2
,但我们也使用^{divider
行替换为空字符串:使用Pandas工具的通用解决方案
好吧,我花了一些时间才弄明白,但我想找到一个圆滑的答案,我有点喜欢这个:
结果:
解决方案
我相信有更好的方法,但这里有一种方法:
输出:
台阶
准备新专栏:
抓住第五排:
使用
repeat_mapping
:分解列表:
注意
repeats
中的每个索引都重复了4次。我们将通过将每个索引增加0, 1, 2, 3
来解决这个问题:最后,
df["B"][repeats.index]
只选择其索引与repeats
索引匹配的行,然后将repeats
的值分配给这些行相关问题 更多 >
编程相关推荐