gpt4 book ai didi

python - 这些 for 循环可以重构吗?

转载 作者:行者123 更新时间:2023-12-03 23:46:34 24 4
gpt4 key购买 nike

我想知道是否有更清洁、更有效的方法来做到这一点。我目前使用两个 for 循环来执行以下操作:

data = {'orig_state': ['TN','TN','TN','TX','TX','IL'],
'orig_state_fn': ['Tennessee','Tennessee','Tennessee','Texas','Texas','Illinois'],
'dest_state': ['CA','TN','TN','TX','IL','CA']
}
df = pd.DataFrame(data,columns=['orig_state','orig_state_fn','dest_state'])

state_options = []
for state in df['orig_state'].unique():
state_options.append({'label': str(df[df['orig_state'] == state]['orig_state_fn'].unique())+" "+str(df[df['orig_state'] == state]['dest_state'].count())
+" Packages",'value':state})
for i in range(len(state_options)):
state_options[i]['label'] = state_options[i]['label'].replace("['", "").replace("']", "")

输出:
state_options>>

[{'label': 'Tennessee 3 Packages', 'value': 'TN'},
{'label': 'Texas 2 Packages', 'value': 'TX'},
{'label': 'Illinois 1 Packages', 'value': 'IL'}]

最佳答案

我们可以做 groupby

df1=df.groupby('orig_state').\
apply(lambda x : x['orig_state_fn'].unique()[0]+' '+str(len(x))+' packages').reset_index()
df1.columns=['value','label']

l=df1.to_dict('r')

关于python - 这些 for 循环可以重构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62379939/

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