也许我理解错了,但是
什么时候
for x in customerNames:
x = DataFrame.loc[DataFrame['customer name'] == x]
x
最后一个列表条目的正确输出是因为您的输出超出了循环的缩进。
import pandas as pd
customer_df = pd.DataFrame.from_items([('A', ['Jean', 'France']), ('B', ['James', 'USA'])],
orient='index', columns=['customer', 'country'])
customer_list = ['James', 'Jean']
for x in customer_list:
x = customer_df.loc[customer_df['customer'] == x]
print(x)
print('now I could append the data to something new')
你会得到输出:
customer country
B James USA
now I could append the data to something new
customer country
A Jean France
now I could append the data to something new
或者,如果你不喜欢使用循环,你可以选择
import pandas as pd
customer_df = pd.DataFrame.from_items([('A', ['Jean', 'France']), ('B', ['James', 'USA']),('C', ['Hans', 'Germany'])],
orient='index', columns=['customer', 'country'])
customer_list = ['James', 'Jean']
print(customer_df[customer_df['customer'].isin(customer_list)])
输出:
customer country
A Jean France
B James USA
df.isin更好的解释在于:如何为Pandas dataframe实现'in'和'not in'