英文:
Split columns names cannot be renamed
问题
I have successfully expanded one address column into four. However, the new dataframe has default column names of integers 0-3. I have tried to rename these columns, but the new dataframe with renamed columns is not reflecting the change. The column names remain integers 0-3.
import pandas as pd
import numpy as np
data = pd.read_csv('/Users/kdavid3mbp/Python/ketamine_data.csv')
data['usecase_one'] = data['usecase_one'].str.replace('For', '', regex=True)
data['usecase_one'] = data['usecase_one'].str.replace(':', '', regex=True)
data['usecase_two'] = data['usecase_two'].str.replace('For', '', regex=True)
data['usecase_two'] = data['usecase_two'].str.replace(':', '', regex=True)
address = data['address'].str.split('\n', expand=True)
new_address = address.rename(columns={
'0': 'Clinic Name',
'1': 'Street',
'2': 'City_State_Country',
'3': 'Misc Address'
})
new_address
输出如下:
英文:
I have successfully expanded one address column into four. However, the new dataframe has default column names of integers 0-3. I have tried to rename these columns, but the new dataframe with renamed columns is not reflecting the change. The column names remain integers 0-3.
import pandas as pd
import numpy as np
data = pd.read_csv('/Users/kdavid3mbp/Python/ketamine_data.csv')
data['usecase_one'] = data['usecase_one'].str.replace('For', '', regex=True)
data['usecase_one'] = data['usecase_one'].str.replace(':', '', regex=True)
data['usecase_two'] = data['usecase_two'].str.replace('For', '', regex=True)
data['usecase_two'] = data['usecase_two'].str.replace(':', '', regex=True)
address = data['address'].str.split('\n', expand=True)
new_address = address.rename(columns={
'0': 'Clinic Name',
'1': 'Street',
'2': 'City_State_Country',
'3': 'Misc Address'
})
new_address
The output is as follows:
答案1
得分: 1
你可以像这样重新分配列标题:
new_address = address.set_axis(['Clinic Name',
'Street',
'City_State_Country',
'Misc Address'], axis=1, copy=False)
注意:
未来警告:DataFrame.set_axis 'inplace' 关键字已被弃用并将在未来版本中删除。请改用
obj = obj.set_axis(..., copy=False)
。
你也可以直接使用columns
属性:
address.columns = ['Clinic Name',
'Street',
'City_State_Country',
'Misc Address']
英文:
you can reassign column headers like so:
new_address = address.set_axis(['Clinic Name',
'Street',
'City_State_Country',
'Misc Address'], axis=1, copy=False)
Note:
> FutureWarning: DataFrame.set_axis 'inplace' keyword is deprecated and
> will be removed in a future version. Use obj = obj.set_axis(...,
instead.
> copy=False)
you could also just use the columns attribute:
address.columns = (['Clinic Name',
'Street',
'City_State_Country',
'Misc Address'])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论