通过这两行使用pandas调用文件后:
import pandas as pd
import numpy as np
df = pd.read_csv('PN_lateral_n_eff.txt', header=None)
df.columns = ["effective_index"]
这是我的输出:
effective_index
0 2.568393573877396+1.139080496494329e-006i
1 2.568398351899841+1.129979376397734e-006i
2 2.568401556986464+1.123872317134941e-006i
之后,我无法使用numpy将其转换为实数。因为,熊猫dtype是对象。我试过这个:
np.real(df, dtype = float)
TypeError:real()得到了一个意外的关键字参数'dtype'
有什么办法吗?
答案 0 :(得分:1)
看起来astype(complex)
适用于Numpy字符串数组,但不适用于Pandas系列对象:
cmplx = df['effective_index'].str.replace('i','j')\ # Go engineering
.values\ # Go NumPy
.astype('str')\ # Go string
.astype(np.complex) # Go complex
#array([ 2.56839357 +1.13908050e-06j, 2.56839835 +1.12997938e-06j,
# 2.56840156 +1.12387232e-06j])
df['effective_index'] = cmplx # Go Pandas again