ba_*_*_ul 11 python tuples pandas
如何转换此数据帧
location value
0 (Richmond, Virginia, nan, USA) 100
1 (New York City, New York, nan, USA) 200
对此:
city state region country value
0 Richmond Virginia nan USA 100
1 New York City New York nan USA 200
请注意,location第一个数据框中的列包含元组.我想在列中创建四列location.
new_col_list = ['city','state','regions','country']
for n,col in enumerate(new_col_list):
df[col] = df['location'].apply(lambda location: location[n])
df = df.drop('location',axis=1)
Run Code Online (Sandbox Code Playgroud)
如果返回一系列(拆分)位置,则可以直接将结果DF与值列合并(join以合并索引).
addr = ['city', 'state', 'region', 'country']
df[['value']].join(df.location.apply(lambda loc: Series(loc, index=addr)))
value city state region country
0 100 Richmond Virginia NaN USA
1 200 New York City New York NaN USA
Run Code Online (Sandbox Code Playgroud)