Pandas: change data type of Series to String
A new answer to reflect the most current practices: as of now (v1.2.4), neither astype('str')
nor astype(str)
work.
As per the documentation, a Series can be converted to the string datatype in the following ways:
df['id'] = df['id'].astype("string")
df['id'] = pandas.Series(df['id'], dtype="string")
df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)
Convert any array of any type into string
Write a utility method like below:
public static String convertToString(Object input){
if (input instanceof Object[]) {
// deepToString used to handle nested arrays.
return Arrays.deepToString((Object[]) input);
} else {
return input.toString();
}
}
Please note that the first if
condition would be evaluated to false
if the input is a primitive array like int[]
, boolean[]
, etc. But it would work for Integer[]
etc.If you want the method to work for primitive arrays, then you need to add conditions for each type separately like:
else if (input instanceof int[]){
// primitive arrays cannot be nested.
// hence Arrays.deepToString is not required.
return Arrays.toString((Object[]) input);
}
How to convert instance of any type to string?
I'm not sure you even need a function, but this would be the shortest way:
function( arg ) {
return arg + '';
}
Otherwise this is the shortest way:arg += '';
Converting a custom type to string in Go
Convert the value to a string:
func SomeFunction() string {
return string(Foobar)
}
Convert to a datatype given in string format
You have to map the strings to a type. Since not all of them are System.<yourType>
directly, I would consider creating a mapping:
Dictionary<string, Type> types = new Dictionary<string, Type>();
types.Add("int", typeof(System.Int32);
//etc.
Then, use Convert.ChangeType to get your object:object myObj = Convert.ChangeType(b, types[a]);
Maybe you could extend this by trying to get the type if the key does not exist in your type mapping:object myObj = Convert.ChangeType(b, Type.GetType("System." + a));
Related Topics
How to Write Utf-8 in a CSV File
How to Plot Empirical Cdf (Ecdf)
Networkx - Change Color/Width According to Edge Attributes - Inconsistent Result
Source Interface with Python and Urllib2
Safely Create a File If and Only If It Does Not Exist with Python
Python Observer Pattern: Examples, Tips
Is There a Simple Process-Based Parallel Map for Python
Python & Pandas: How to Query If a List-Type Column Contains Something
Syntax Error: Invalid Syntax' for No Apparent Reason
Pandas Dataframe Aggregate Function Using Multiple Columns
Pip Is Not Able to Install Packages Correctly: Permission Denied Error
How to Skip Iterations in a Loop
How to Include Image Files in Django Templates
Fitting a Closed Curve to a Set of Points
Scipy Curve_Fit Doesn't Like Math Module
How to Get Precision, Recall and F-Measure from Confusion Matrix in Python