我想使用pandas通过连接数据框中的其他2列来填充列。
输入表
City State
Boston MA
Austin TX
我想添加一个“位置”列 输入表
City State Location
Boston MA Boston, MA
Austin TX Austin, TX
目前,这是我正在使用的代码:
df['Location'] = None
for i in range(len(df)):
df.Location[i] = str(df.loc[i, 'City']) + ", " + str(df.loc[i, 'State'])
我尝试过使用这两种方法:
df['Location'] = '{}, {}'.format(str(df['City']), str(df['State']))
df['Location'] = str(df['City']) + ', ' + str(df['State'])
但只得到这个输出:
City State Location
Boston MA Boston
Austin TX Austin
如果您还可以解释为什么我会得到这些结果,那将有助于我将来对大熊猫的理解。
答案 0 :(得分:3)
使用矢量化字符串连接非常简单。
df['Location'] = df.City + ', ' + df.State
City State Location
0 Boston MA Boston, MA
1 Austin TX Austin, TX