![](/img/trans.png)
[英]Multi tab Excel sheets, unique entries in 1 column, create new file with data from another column as the name, all with headers
[英]Pandas create new column with all the entries from another column corresponding to a unique value
如果問題不夠清楚,我很抱歉。 假設我有這個 dataframe:
timestamp source dest size
1 a b 5
1 c d 6
2 c e 7
2 d a 8
從這個 dataframe 我想要這樣的東西:
timestamp link size
1 a b c d 5 6
2 c e d a 7 8
我怎樣才能做到這一點?
謝謝
這是一個帶有幾個附加步驟的 pivot,因為您希望 pivot 在兩列上彼此獨立。
u = df.melt('timestamp')
m = u['variable'].isin(['source', 'dest'])
u.loc[m, 'variable'] = 'link'
u.pivot_table(
'value', 'timestamp', 'variable', aggfunc=list)
variable link size
timestamp
1 [a, c, b, d] [5, 6]
2 [c, d, e, a] [7, 8]
首先使用rename
的替代方法
d = dict(source='link', dest='link')
df.rename(columns=d).melt('timestamp').pivot_table(
'value', 'timestamp', 'variable', aggfunc=list)
variable link size
timestamp
1 [a, c, b, d] [5, 6]
2 [c, d, e, a] [7, 8]
您也可以使用 pandas dataframe 的groupby
方法。 確保您的size
列包含字符串。
df['link'] = df['source'] + ' ' + df['dest']
df = df.drop(['source', 'dest'], axis = 1)
newDf = df.groupby('timestamp').agg(lambda col: ' '.join(col))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.