樣本資料:
sample = pd.DataFrame({'split_me': [1.5, 2, 4, 3.2], 'copy_me': ['A', 'B', 'C', 'D']})
out = pd.DataFrame({'split_me': [1, 0.5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.2], 'copy_me': ['A', 'A', 'B', 'B', 'C', 'C', 'C', 'C', 'D', 'D', 'D', 'D']})
sample: # input
split_me copy_me
0 1.5 A
1 2.0 B
2 4.0 C
3 3.2 D
out: # desired output
split_me copy_me
0 1.0 A
1 0.5 A
2 1.0 B
3 1.0 B
4 1.0 C
5 1.0 C
6 1.0 C
7 1.0 C
8 1.0 D
9 1.0 D
10 1.0 D
11 0.2 D
我嘗試使用類似sample.loc[sample.index.repeat(sample['split_me'])]. 然而,這僅對整數重復,當我需要它回傳 2 時,像 1.9 這樣的值回傳 1 行,并且它使值split_me保持不變,而我需要復制行,split_me如果它大于 1,則分配 1,否則分配值.
我想不出一種方法來做到這一點而不會變得混亂和復雜,我最好的方法是ceil(split_me)然后運行repeat,但我仍然需要一種方法來將值分配給重復的行。如果有人有的話,尋找更簡單的解決方案。
uj5u.com熱心網友回復:
是的,我們可以做到這一點
out = sample.reindex(sample.index.repeat(np.ceil(sample['split_me'])))
out['new'] = 1
con = ~out['copy_me'].duplicated(keep='last') & (out['split_me']%1!=0)
out['new'] = out['new'].mask(con, out['split_me']%1)
out
Out[195]:
split_me copy_me new
0 1.5 A 1.0
0 1.5 A 0.5
1 2.0 B 1.0
1 2.0 B 1.0
2 4.0 C 1.0
2 4.0 C 1.0
2 4.0 C 1.0
2 4.0 C 1.0
3 3.2 D 1.0
3 3.2 D 1.0
3 3.2 D 1.0
3 3.2 D 0.2
uj5u.com熱心網友回復:
使用自定義重復功能
repeat_float = lambda x: ([1.] * int(x // 1)) ([x % 1] if x % 1 != 0 else [])
out = df['split_me'].apply(repeat_float).explode().astype(float) \
.to_frame().join(df['copy_me']).reset_index(drop=True)
輸出:
>>> out
split_me copy_me
0 1.0 A
1 0.5 A
2 1.0 B
3 1.0 B
4 1.0 C
5 1.0 C
6 1.0 C
7 1.0 C
8 1.0 D
9 1.0 D
10 1.0 D
11 0.2 D
uj5u.com熱心網友回復:
我們可以使用np.modf將 的小數部分和整數部分分開split_me,然后根據repeat整數部分的唯一 來創建一個新的 1 系列。append非零小數部分,sort_index進入預期的順序,最后join回傳列并reset_index恢復范圍索引:
fractional, integral = np.modf(sample['split_me'])
df = (
pd.Series(1, index=integral.index.repeat(integral), name=integral.name)
.append(fractional[fractional.ne(0)]).sort_index(kind='stable')
.to_frame().join(sample[['copy_me']]).reset_index(drop=True)
)
df:
split_me copy_me
0 1.0 A
1 0.5 A
2 1.0 B
3 1.0 B
4 1.0 C
5 1.0 C
6 1.0 C
7 1.0 C
8 1.0 D
9 1.0 D
10 1.0 D
11 0.2 D
設定和匯入:
import numpy as np
import pandas as pd
sample = pd.DataFrame({
'split_me': [1.5, 2, 4, 3.2],
'copy_me': ['A', 'B', 'C', 'D']
})
uj5u.com熱心網友回復:
嘗試:
import pandas as pd
import numpy as np
sample = pd.DataFrame({'split_me': [1.5, 2, 4, 3.2], 'copy_me': ['A', 'B', 'C', 'D']})
def expanded_index(s, c):
index = np.repeat(1.0, s // 1)
if (s % 1) > 0:
index = np.append(index, [s % 1])
return pd.Series(c, index)
res = pd.concat([expanded_index(s, c) for s, c in zip(sample["split_me"], sample["copy_me"])])
print(res)
輸出
1.0 A
0.5 A
1.0 B
1.0 B
1.0 C
1.0 C
1.0 C
1.0 C
1.0 D
1.0 D
1.0 D
0.2 D
dtype: object
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/340440.html
上一篇:Discord.py-為什么我的機器人將每條訊息發送兩次?
下一篇:在時間序列資料中插入行作為分隔符
