我正在從 csv 檔案中讀取資料,并且在我的資料框中有當前值,其中寬度和高度是最小值和最大值。
name width heigth
apple [10, 20] [15, 18]
現在我想拆分和格式化列并列印它們:
pd.DataFrame(df['width'].str.split(',').tolist(), columns=['width-min', 'width-max'])
pd.DataFrame(df['height'].str.split(',').tolist(), columns=['height-min', 'height-max'])
print(tabulate(df, headers='keys', tablefmt='psql'))
我的問題是它仍然列印:
name width heigth
apple [10, 20] [15, 18]
而我希望它列印:
name min-width max-width min-height max-height
apple 10 20 15 18
我究竟做錯了什么?
uj5u.com熱心網友回復:
這段代碼可以幫助你,
a = {"name":['apple'],
'width': ['[10, 20]'],
'heigth': ['[15, 18]']}
import pandas as pd
df = pd.DataFrame(a)
df['min-width'], df['max-width'] = df['width'].apply(lambda x: x.strip('][').split(', ')[0]), \
df['width'].apply(lambda x: x.strip('][').split(', ')[1])
df['min-height'], df['max-height'] = df['heigth'].apply(lambda x: x.strip('][').split(', ')[0]), \
df['heigth'].apply(lambda x: x.strip('][').split(', ')[1])
df = df.drop(['width','heigth'],axis=1)
將df是,
name min-width max-width min-height max-height
0 apple 10 20 15 18
如果這對你有幫助,請告訴我!另外,我愿意接受優化的建議!!
uj5u.com熱心網友回復:
您不保存生成的 df。您需要將修改后的 df 分配給新變數或覆寫原始變數。
編輯:
#create a separate df for each split operation (height and width separately)
df_1 = pd.DataFrame(df['width'].str.split(',').tolist(), columns=['width-min', 'width-max'])
df_2 = pd.DataFrame(df['height'].str.split(',').tolist(), columns=['height-min', 'height-max'])
# join the two dataframes on a common index or column
pd.merge(df_1, df_2, on=["enter common column here"])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/456042.html
