出现TypeError:期望str实例却得到Timestamp,如何修改Pandas代码?
Got it, let's break down what's happening here. The error is telling you that one of the values in your expectedsheetkeycols columns is a Timestamp object, not a string — and ''.join() only works with string sequences. So we need to convert all the values in those columns to strings before joining them up.
Here are a few straightforward fixes depending on your needs:
1. Quick Fix: Convert all values to strings in the lambda
Just wrap each item in str() as you iterate through the row:
sheet1['KEY_COLUMN'] = sheet1[expectedsheetkeycols].apply(lambda x: ''.join(str(item) for item in x), axis=1)
This is simple and works if you're okay with the default string representation of your Timestamp (like 2024-05-20 00:00:00).
2. Cleaner Approach: Convert the entire subset to strings first
You can use astype(str) to convert all columns in your subset to string type upfront, then apply the join — this makes the lambda cleaner:
sheet1['KEY_COLUMN'] = sheet1[expectedsheetkeycols].astype(str).apply(lambda x: ''.join(x), axis=1)
This is great if all columns in expectedsheetkeycols can safely be converted to strings without losing important formatting.
3. Custom Timestamp Formatting (If You Need It)
If you don't want the default Timestamp string (maybe you just want YYYYMMDD instead of the full datetime), you can write a small helper function to handle formatting explicitly:
import pandas as pd def build_key(row): key_components = [] for col_name in expectedsheetkeycols: value = row[col_name] # Check if the value is a Timestamp if isinstance(value, pd.Timestamp): # Use strftime to format it however you want key_components.append(value.strftime('%Y%m%d')) else: # Convert other values to string normally key_components.append(str(value)) return ''.join(key_components) sheet1['KEY_COLUMN'] = sheet1[expectedsheetkeycols].apply(build_key, axis=1)
This gives you full control over how your timestamp is represented in the key, which is super useful if you need consistent formatting for matching later.
Any of these should resolve that TypeError — pick the one that fits your use case best!
内容的提问来源于stack exchange,提问作者Kumar Prvn

