也许我误会了你,但是
什么时候
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 更好解释:How to implement 'in' and 'not in' for Pandas dataframe