我的data1如下:

[
{"cut_id":1,"cut_label":"v024","cut_name":"State","value_label":"1","value":"andaman and nicobar islands"},
{"cut_id":3,"cut_label":"v024","cut_name":"State","value_label":"3","value":"arunachal pradesh"},
{"cut_id":635,"cut_label":"sdistri","cut_name":"District","value_label":"599","value":"pathanamthitta"},
{"cut_id":636,"cut_label":"sdistri","cut_name":"District","value_label":"600","value":"kollam"},
{"cut_id":637,"cut_label":"sdistri","cut_name":"District","value_label":"601","value":"thiruvananthapuram"}
]


我想要的输出如下:

[
{"value_label":"S1","value":"andaman and nicobar islands"},
{"value_label":"S3","value":"arunachal pradesh"},
{"value_label":"D599","value":"pathanamthitta"},
{"value_label":"D600","value":"kollam"},
{"value_label":"D601","value":"thiruvananthapuram"}
]


我的意图是通过根据数字是州还是区,在数字后附加一个字符“ S”或“ D”来重命名值标签。

这是我的代码:

for _, r in data[
        (data['cut_name'] == 'State') | (data['cut_name'] == 'District')][
            ['cut_name', 'value', 'value_label']
    ].iterrows():
    cuts_data[r.cut_name[0]+r.value_label] = r.value


我得到了预期的结果,但是有一种方法可以做到这一点

最佳答案

str与索引一起使用以获取cut_name的第一个值,并在必要时通过Series.isin对其进行过滤:

mask = data['cut_name'].isin(['State','District'])
data.loc[mask, 'value_label'] = data['cut_name'].str[0] + data['value_label'].astype(str)


如果仅StateDistrict可能的值:

data['value_label'] = data['cut_name'].str[0] + data['value_label'].astype(str)


为了提高性能,可以使用列表理解(正常工作是不丢失值):

data['value_label'] = [c[0] + str(v) for c, v in zip(data['cut_name'], data['value_label'])]


如果需要带有过滤列的新DataFrame:

new_df = data[['value','value_label']]

关于python - 如何将迭代下的功能转换为 Pandas 中的一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55449388/

10-12 05:31