Pandas筛选数据后索引去除及目录匹配代码问题求助
Hey there! Let's work through your two Pandas-related issues step by step:
The root issue here is that your current code appends a Pandas Series object (from App['Address']) to df_address, rather than a plain list of strings. That's why printing df_address shows the index. Here are two straightforward fixes:
Option 1: Generate a clean list of addresses upfront
Rewrite your initial code to directly get a list of address strings, so you won't have to deal with indexes at all:
import pandas as pd df = pd.read_csv('Information.csv', index_col=False) # Filter rows for Rony, extract the Address column, and convert it to a list df_address = df[df['Names'] == 'Rony']['Address'].tolist() # Now printing will show just the addresses without any indexes print(df_address)
Option 2: Fix printing for your existing df_address
If you need to keep your original code structure, you can convert the Series to a string without indexes when printing:
# Iterate through each Series in your df_address list for addr_series in df_address: # Print the Series content without the index print(addr_series.to_string(index=False))
Your current loop fails because df_address contains Pandas Series objects, not plain strings. Comparing these Series to the directory names in dct won't yield matches. Here's how to fix it:
Fixed full code
import os import pandas as pd # Step 1: Get a clean list of addresses for Rony df = pd.read_csv('Information.csv', index_col=False) df_address = df[df['Names'] == 'Rony']['Address'].tolist() # Step 2: Get the list of subdirectories in the current folder dct = next(os.walk('.'))[1] # Step 3: Check each address against the directory list for addr in df_address: if addr in dct: # Replace this with your actual operation print(f"Found matching directory: {addr}") # Do Some operation
If you can't change how df_address is generated
If you have to retain the original df_address (which holds Series objects), unpack the Series first in the loop:
for addr_series in df_address: # Convert the Series to a list of strings addresses = addr_series.tolist() for addr in addresses: if addr in dct: # Do Some operation print(f"Matched directory: {addr}")
内容的提问来源于stack exchange,提问作者steveJ

