Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

pandas - Check if dataframe column contain string type in Python

I have a dataframe as such:

enter image description here

If column 1 is a string, i need column 2, else column 1 still.

Tried this:

df.loc[df[1].dtype != np.number, df[1]] = df.loc[df[1].dtype != np.number, df[1]]  

But it gives me a key error: True

question from:https://stackoverflow.com/questions/65937992/check-if-dataframe-column-contain-string-type-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

List comprehension might come handy in such case, check out:

df = pd.DataFrame()
df[0] = ["some", "dummy", "data", "filling", "up"]
df[1] = ["0","foo","2","3","bar"]
df[2] = [9,8,7,6,5]
df[3] = [item[1][1] if item[1][1].isnumeric() else item[1][2] for item in df.iterrows() ]

Assign new row with item from row 1 if it is numeric, else use item from row 2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...