如何从 pandas 中的多个数据框中搜索值和 return 行?
How to search a value and return the row from multiple dataframes in pandas?
例如,如果我有多个数据帧,如 df1、df2 和 df3。我在每个数据框中都有一列 'phone_no' 。我如何在每个数据帧中搜索 phone_no 和 return 该数据帧所在的行?
例如
df_all = [df1, df2, df3]
for i in df_all:
print(i.loc[i['phone_no'] == 9999999999])
以上代码是return空输出。输出必须是 phone_no 包含特定 phone 数字的行。如何解决这个问题?
通过将 phone_no
与字符串进行比较来检查这是否有效:
df_all = [df1, df2, df3]
for i in df_all:
print(i.loc[i['phone_no'].astype(str) == '9999999999'])
也许您不需要将 phone_no
转换为 str
,如果已经是这样的话。您必须检查:
>>> print(df1['phone_no'].dtype)
object
# OR
>>> print(df1['phone_no'].dtype)
int64
更新
df_all = [df1, df2, df3]
df_filtered = []
for i in df_all:
df_filtered.append(i.loc[i['phone_no'].astype(str) == '9999999999'])
例如,如果我有多个数据帧,如 df1、df2 和 df3。我在每个数据框中都有一列 'phone_no' 。我如何在每个数据帧中搜索 phone_no 和 return 该数据帧所在的行?
例如
df_all = [df1, df2, df3]
for i in df_all:
print(i.loc[i['phone_no'] == 9999999999])
以上代码是return空输出。输出必须是 phone_no 包含特定 phone 数字的行。如何解决这个问题?
通过将 phone_no
与字符串进行比较来检查这是否有效:
df_all = [df1, df2, df3]
for i in df_all:
print(i.loc[i['phone_no'].astype(str) == '9999999999'])
也许您不需要将 phone_no
转换为 str
,如果已经是这样的话。您必须检查:
>>> print(df1['phone_no'].dtype)
object
# OR
>>> print(df1['phone_no'].dtype)
int64
更新
df_all = [df1, df2, df3]
df_filtered = []
for i in df_all:
df_filtered.append(i.loc[i['phone_no'].astype(str) == '9999999999'])