亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Pandas 將字符串與 groupby 結合起來

Pandas 將字符串與 groupby 結合起來

千巷貓影 2022-11-01 16:55:36
我正在嘗試在我的數據框中組合字符串。數據框如下所示:0          code   text11        507489   text22        507489   text33        506141   text44        506141   text55        504273   text6我當前的代碼:import pandas as pddf = pd.read_csv("location.csv", header=None, delimiter=';', dtype='unicode', nrows=100)new_header = df.iloc[0] df = df[1:] df.columns = new_headerdf.groupby('code').agg('->'.join).reset_index()df.to_csv (r'new_location\export_dataframe.csv', index = False, header=True)print(df)但我沒有得到預期的結果。當我期待時,輸出看起來與輸入相同:0          code   text11        507489   text2->text32        506141   text4->text53        504273   text6對此很陌生,所以我一定犯了一些簡單的錯誤。產生相同結果的數據框:testf = {'code': ['1','2','2','4'],        'text': [22000,25000,27000,35000]        }df = pd.DataFrame(testf, columns = ['code', 'text'])
查看完整描述

1 回答

?
楊__羊羊

TA貢獻1943條經驗 獲得超7個贊

似乎您忘記了分配回來,也被刪除header=None了,read_csv因為在文件中是用于 DataFrame 中列名稱的標題:


import pandas as pd


df = pd.read_csv("location.csv", sep=';', dtype='unicode', nrows=100)


df = df.groupby('code').agg('->'.join).reset_index()

print (df)

     code         text1

0  504273         text6

1  506141  text4->text5

2  507489  text2->text3


df.to_csv (r'new_location\export_dataframe.csv', index = False)


查看完整回答
反對 回復 2022-11-01
  • 1 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號