gpt4 book ai didi

python - 当且仅当标题字符串中包含 '20' 时,遍历每个数据帧标题并将 int month 更新为 str month

转载 作者:行者123 更新时间:2023-11-28 16:58:08 26 4
gpt4 key购买 nike

一些需要更改 df header 的 Django 格式问题。

测试数据:

Test_Data = [
('Year_Month', ['Done_RFQ','Not_Done_RFQ','Total_RFQ']),
('2018_11', [10, 20, 30]),
('2019_06',[10,20,30]),
('2019_12', [40, 50, 60]),
]

df = pd.DataFrame(dict(Test_Data))
print(df)

Year_Month 2018_11 2019_06 2019_12
0 Done_RFQ 10 10 40
1 Not_Done_RFQ 20 20 50
2 Total_RFQ 30 30 60

期望的输出:

     Year_Month  2018_Nov  2019_Jun  2019_Dec
0 Done_RFQ 10 10 40
1 Not_Done_RFQ 20 20 50
2 Total_RFQ 30 30 60

我的尝试:

df_names = df.columns
for df_name in df_names:
if df_name[:1] == '20':
df.df_name = str(pd.to_datetime(df_name, format='%Y_%m').dt.strftime('%Y_%b'))

错误:AttributeError:“Timestamp”对象没有属性“dt”

我希望日期对象可以用于格式化。关于如何对 header 中的任何字符串进行通用化的任何建议?

最佳答案

国际联合会

s=pd.Series(df.columns)
s2=pd.to_datetime(s,format='%Y_%m',errors ='coerce').dt.strftime('%Y_%b')
df.columns=s2.mask(s2=='NaT').fillna(s)
df
Out[368]:
2018_Nov 2019_Jun 2019_Dec Year_Month
0 10 10 40 Done_RFQ
1 20 20 50 Not_Done_RFQ
2 30 30 60 Total_RFQ

关于python - 当且仅当标题字符串中包含 '20' 时,遍历每个数据帧标题并将 int month 更新为 str month,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56266607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com