我有一个数据框,其中一列是包含地址信息的列表
我的数据:
import pandas as pd
data = [['location1', [(123, 'Number'),('Main', 'Street'),('New York', 'City')]], ['location2', [('Broadway', 'Street'),('New York', 'City'),(11111, 'ZIP')]], ['location3', [(987, 'Number'),('Grand', 'Street'),('Chicago', 'City'), (55555,'ZIP')]]]
df = pd.DataFrame(data, columns = ['Location', 'Address_Info'])
这将创建一个如下所示的数据帧:
Location Address_Info
0 location1 [(123, 'Number'), ('Main', 'Street'), ('New York', 'City')]
1 location2 [('Broadway', 'Street'), ('New York', 'City'), (11111, 'ZIP')]
2 location3 [(987, 'Number'), ('Grand', 'Street'), ('Chicago', 'City'), (55555, 'ZIP')]
我需要提取包含“Number”值的列表。然后,我需要将该列表中的数字添加到新列中的数据框中
生成的数据帧如下所示:
Location Address_Info Number
0 location1 [(123, 'Number'), ('Main', 'Street'), ('New York', 'City')] 123
1 location2 [('Broadway', 'Street'), ('New York', 'City'), (11111, 'ZIP')] NaN
2 location3 [(987, 'Number'), ('Grand', 'Street'), ('Chicago', 'City'), (55555, 'ZIP')] 987
我遇到的一个问题是“地址信息”中没有包含“号码”的列表
将列表分解为行,然后将元组展开为列,并仅保留带有
Number
的行您可以使用列表理解和
str
访问器:输出:
要将其保存在新列中,请执行以下操作:
NB。如果您需要几个数字,可以省略
.str[0]
,然后您将得到一个数字列表(如果没有,则为空):输出:
在创建DF之前准备好数据
输出
相关问题 更多 >
编程相关推荐